{"id":19857928,"url":"https://github.com/googlecontainertools/container-structure-test","last_synced_at":"2025-05-12T15:29:42.666Z","repository":{"id":39618330,"uuid":"108044834","full_name":"GoogleContainerTools/container-structure-test","owner":"GoogleContainerTools","description":"validate the structure of your container images","archived":false,"fork":false,"pushed_at":"2025-04-07T06:23:07.000Z","size":5860,"stargazers_count":2378,"open_issues_count":88,"forks_count":200,"subscribers_count":56,"default_branch":"main","last_synced_at":"2025-04-23T17:17:52.226Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GoogleContainerTools.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":"CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-10-23T21:57:40.000Z","updated_at":"2025-04-23T05:44:44.000Z","dependencies_parsed_at":"2023-10-13T11:11:12.608Z","dependency_job_id":"bac217a9-9725-44d4-a3c6-52222a4dadef","html_url":"https://github.com/GoogleContainerTools/container-structure-test","commit_stats":{"total_commits":295,"total_committers":58,"mean_commits":5.086206896551724,"dds":0.6067796610169491,"last_synced_commit":"72d2f270fd3c6705d3fe751cee48089104e591e6"},"previous_names":["googlecloudplatform/container-structure-test"],"tags_count":36,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleContainerTools%2Fcontainer-structure-test","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleContainerTools%2Fcontainer-structure-test/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleContainerTools%2Fcontainer-structure-test/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleContainerTools%2Fcontainer-structure-test/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GoogleContainerTools","download_url":"https://codeload.github.com/GoogleContainerTools/container-structure-test/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253765562,"owners_count":21960755,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-12T14:20:18.566Z","updated_at":"2025-05-12T15:29:42.626Z","avatar_url":"https://github.com/GoogleContainerTools.png","language":"Go","readme":"Container Structure Tests\n====================\n\nThe Container Structure Tests provide a powerful framework to validate the structure\nof a container image. These tests can be used to check the output of commands\nin an image, as well as verify metadata and contents of the filesystem.\n\nTests can be run either through a standalone binary, or through a Docker image.\n\n**Note: container-structure-test is not an officially supported Google project, and is currently in maintainence mode. Contributions are still welcome!**\n\n## Installation\n\n### OS X\n\nInstall via [brew](https://brew.sh/):\n\n```bash\n$ brew install container-structure-test\n```\n\n```shell\ncurl -LO https://github.com/GoogleContainerTools/container-structure-test/releases/latest/download/container-structure-test-darwin-arm64 \u0026\u0026 chmod +x container-structure-test-darwin-arm64 \u0026\u0026 sudo mv container-structure-test-darwin-arm64 /usr/local/bin/container-structure-test\n```\n\n### Linux\n```shell\ncurl -LO https://github.com/GoogleContainerTools/container-structure-test/releases/latest/download/container-structure-test-linux-amd64 \u0026\u0026 chmod +x container-structure-test-linux-amd64 \u0026\u0026 sudo mv container-structure-test-linux-amd64 /usr/local/bin/container-structure-test\n```\n\nIf you want to avoid using sudo:\n\n```shell\ncurl -LO https://github.com/GoogleContainerTools/container-structure-test/releases/latest/download/container-structure-test-linux-amd64 \u0026\u0026 chmod +x container-structure-test-linux-amd64 \u0026\u0026 mkdir -p $HOME/bin \u0026\u0026 export PATH=$PATH:$HOME/bin \u0026\u0026 mv container-structure-test-linux-amd64 $HOME/bin/container-structure-test\n```\n\n\u003e [!warning]\n\u003e Container builds are currently not updated with new releases\n\nAdditionally, a container image for running tests through Google Cloud Builder can be found\nat `gcr.io/gcp-runtimes/container-structure-test:latest`.\n\n## Setup\nTo use container structure tests to validate your containers, you'll need the following:\n- The container structure test binary or docker image\n- A container image to test against\n- A test `.yaml` or `.json` file with user defined structure tests to run inside of the specified container image\n\nNote that the test framework looks for the provided image in the local Docker\ndaemon (if it is not provided as a tar). The `--pull` flag can optionally\nbe provided to force a pull of a remote image before running the tests.\n\n## Example Run\nAn example run of the test framework:\n```shell\ncontainer-structure-test test --image gcr.io/registry/image:latest \\\n--config config.yaml\n```\n\nTests within this framework are specified through a YAML or JSON config file,\nwhich is provided to the test driver via a CLI flag. Multiple config files may\nbe specified in a single test run. The config file will be loaded in by the\ntest driver, which will execute the tests in order. Within this config file,\nfour types of tests can be written:\n\n- Command Tests (testing output/error of a specific command issued)\n- File Existence Tests (making sure a file is, or isn't, present in the\nfile system of the image)\n- File Content Tests (making sure files in the file system of the image\ncontain, or do not contain, specific contents)\n- Metadata Test, *singular* (making sure certain container metadata is correct)\n\n## Command Tests\nCommand tests ensure that certain commands run properly in the target image.\nRegexes can be used to check for expected or excluded strings in both `stdout`\nand `stderr`. Additionally, any number of flags can be passed to the argument\nas normal. Each command in the setup section will run in a separate container\nand then commits a modified image to be the new base image for the test run.\n\n#### Supported Fields:\n\n**NOTE: `schemaVersion` must be specified in all container-structure-test yamls. The current version is `2.0.0`.**\n\n- Name (`string`, **required**): The name of the test\n- Setup (`[][]string`, *optional*): A list of commands\n(each with optional flags) to run before the actual command under test.\n- Teardown (`[][]string`, *optional*): A list of commands\n(each with optional flags) to run after the actual command under test.\n- Command (`string`, **required**): The command to run in the test.\n- Args (`[]string`, *optional*): The arguments to pass to the command.\n- EnvVars (`[]EnvVar`, *optional*): A list of environment variables to set for\nthe individual test. See the **Environment Variables** section for more info.\n- Expected Output (`[]string`, *optional*): List of regexes that should\nmatch the stdout from running the command.\n- Excluded Output (`[]string`, *optional*): List of regexes that should **not**\nmatch the stdout from running the command.\n- Expected Error (`[]string`, *optional*): List of regexes that should\nmatch the stderr from running the command.\n- Excluded Error (`[]string`, *optional*): List of regexes that should **not**\nmatch the stderr from running the command.\n- Exit Code (`int`, *optional*): Exit code that the command should exit with.\n\nExample:\n```yaml\ncommandTests:\n  - name: \"gunicorn flask\"\n    setup: [[\"virtualenv\", \"/env\"], [\"pip\", \"install\", \"gunicorn\", \"flask\"]]\n    command: \"which\"\n    args: [\"gunicorn\"]\n    expectedOutput: [\"/env/bin/gunicorn\"]\n  - name:  \"apt-get upgrade\"\n    command: \"apt-get\"\n    args: [\"-qqs\", \"upgrade\"]\n    excludedOutput: [\".*Inst.*Security.* | .*Security.*Inst.*\"]\n    excludedError: [\".*Inst.*Security.* | .*Security.*Inst.*\"]\n```\n\nDepending on your command the argument section can get quite long. Thus, you\ncan make use of YAML's list style option for separation of arguments and the\nliteral style option to preserve newlines like so:\n\n```shell\ncommandTests:\n  - name: \"say hello world\"\n    command: \"bash\"\n    args:\n      - -c\n      - |\n         echo hello \u0026\u0026\n         echo world\n```\n\n### Image Entrypoint\n\nTo avoid unexpected behavior and output when running commands in the\ncontainers, **all entrypoints are overwritten by default.** If your\nentrypoint is necessary for the structure of your container, use the\n`setup` field to call any scripts or commands manually before running\nthe tests.\n\n```yaml\ncommandTests:\n  ...\n  setup: [[\"my_image_entrypoint.sh\"]]\n  ...\n```\n\n### Intermediate Artifacts\nEach command test run creates either a container (with the `docker` driver) or\ntar artifact (with the `tar` driver). By default, these are deleted after the\ntest run finishes, but the `--save` flag can optionally be passed to keep\nthese around. This would normally be used for debugging purposes.\n\n\n## File Existence Tests\nFile existence tests check to make sure a specific file (or directory) exist\nwithin the file system of the image. No contents of the files or directories\nare checked. These tests can also be used to ensure a file or directory is\n**not** present in the file system.\n\n#### Supported Fields:\n\n- Name (`string`, **required**): The name of the test\n- Path (`string`, **required**): Path to the file or directory under test\n- ShouldExist (`boolean`, **required**): Whether or not the specified file or\ndirectory should exist in the file system\n- Permissions (`string`, *optional*): The expected Unix permission string (e.g.\n  drwxrwxrwx) of the files or directory.\n- Uid (`int`, *optional*): The expected Unix user ID of the owner of the file\n  or directory.\n- Gid (`int`, *optional*): The expected Unix group ID of the owner of the file or directory.\n- IsExecutableBy (`string`, *optional*): Checks if file is executable by a given user.\n  One of `owner`, `group`, `other` or `any`\n\nExample:\n```yaml\nfileExistenceTests:\n- name: 'Root'\n  path: '/'\n  shouldExist: true\n  permissions: '-rw-r--r--'\n  uid: 1000\n  gid: 1000\n  isExecutableBy: 'group'\n```\n\n## File Content Tests\nFile content tests open a file on the file system and check its contents.\nThese tests assume the specified file **is a file**, and that it **exists**\n(if unsure about either or these criteria, see the above\n**File Existence Tests** section). Regexes can again be used to check for\nexpected or excluded content in the specified file.\n\n#### Supported Fields:\n\n- Name (`string`, **required**): The name of the test\n- Path (`string`, **required**): Path to the file under test\n- ExpectedContents (`string[]`, *optional*): List of regexes that\nshould match the contents of the file\n- ExcludedContents (`string[]`, *optional*): List of regexes that\nshould **not** match the contents of the file\n\nExample:\n```yaml\nfileContentTests:\n- name: 'Debian Sources'\n  path: '/etc/apt/sources.list'\n  expectedContents: ['.*httpredir\\.debian\\.org.*']\n  excludedContents: ['.*gce_debian_mirror.*']\n```\n\n## Metadata Test\nThe Metadata test ensures the container is configured correctly. All\nof these checks are optional.\n\n#### Supported Fields:\n\n- EnvVars (`[]EnvVar`): A list of environment variable key/value pairs that should be set\nin the container. isRegex (*optional*) interpretes the value as regex.\n- UnboundEnvVars (`[]EnvVar`): A list of environment variable keys that should **NOT** be set\nin the container.\n- Labels (`[]Label`): A list of image labels key/value pairs that should be set on the\ncontainer. isRegex (*optional*) interpretes the value as regex.\n- Entrypoint (`[]string`): The entrypoint of the container.\n- Cmd (`[]string`): The CMD specified in the container.\n- Exposed Ports (`[]string`): The ports exposed in the container.\n- Unexposed Ports (`[]string`): The ports **NOT** exposed in the container.\n- Volumes (`[]string`): The volumes exposed in the container.\n- UnmountedVolumes (`[]string`): The volumes **NOT** exposed in the container.\n- Workdir (`string`): The default working directory of the container.\n- User (`user`): The default user of the container.\n\nExample:\n```yaml\nmetadataTest:\n  envVars:\n    - key: foo\n      value: baz\n  labels:\n    - key: 'com.example.vendor'\n      value: 'ACME Incorporated'\n    - key: 'build-date'\n      value: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{6}$'\n      isRegex: true\n  exposedPorts: [\"8080\", \"2345\"]\n  volumes: [\"/test\"]\n  entrypoint: []\n  cmd: [\"/bin/bash\"]\n  workdir: \"/app\"\n  user: \"luke\"\n```\n\n## License Tests\nLicense tests check a list of copyright files and makes sure all licenses are\nallowed at Google. By default it will look at where Debian lists all copyright\nfiles, but can also look at an arbitrary list of files.\n\n#### Supported Fields:\n\n- Debian (`bool`, **required**): If the image is based on Debian, check where\n  Debian lists all licenses.\n- Files (`string[]`, *optional*): A list of other files to check.\n\nExample:\n```yaml\nlicenseTests:\n- debian: true\n  files: [\"/foo/bar\", \"/baz/bat\"]\n```\n\n### Environment Variables\nA list of environment variables can optionally be specified as part of the\ntest setup. They can either be set up globally (for all test runs), or\ntest-local as part of individual command test runs (see the **Command Tests**\nsection above). Each environment variable is specified as a key-value pair.\nUnix-style environment variable substitution is supported.\n\nTo specify, add a section like this to your config:\n\n```yaml\nglobalEnvVars:\n  - key: \"VIRTUAL_ENV\"\n    value: \"/env\"\n  - key: \"PATH\"\n    value: \"/env/bin:$PATH\"\n```\n\n### Additional Options\nThe following fields are used to control various options and flags that may be\ndesirable to set for the running container used to perform a structure test \nagainst an image. This allows an image author to validate certain runtime\nbehavior that cannot be modified in the image-under-test such as running a \ncontainer with an alternative user/UID or mounting a volume.\n\nNote that these options are currently only supported with the `docker` driver.\n\nThe following list of options are currently supported:\n```yaml\ncontainerRunOptions:\n  user: \"root\"                  # set the --user/-u flag\n  privileged: true              # set the --privileged flag (default: false)\n  allocateTty: true             # set the --tty flag (default: false)\n  envFile: path/to/.env         # load environment variables from file and pass to container (equivalent to --env-file)\n  envVars:                      # if not empty, read each envVar from the environment and pass to test (equivalent to --env/e)\n    - SECRET_KEY_FOO\n    - OTHER_SECRET_BAR\n  capabilities:                 # Add list of Linux capabilities (--cap-add)\n    - NET_BIND_SERVICE\n  bindMounts:                   # Bind mount a volume (--volume, -v)\n    - /etc/example/dir:/etc/dir\n```\n\n## Running Tests On [Google Cloud Build](https://cloud.google.com/cloud-build/docs/)\n\nThis tool is released as a builder image, tagged as\n`gcr.io/gcp-runtimes/container-structure-test`, so you can specify tests in your\n`cloudbuild.yaml`:\n\n```yaml\n\nsteps:\n# Build an image.\n- name: 'gcr.io/cloud-builders/docker'\n  args: ['build', '-t', 'gcr.io/$PROJECT_ID/image', '.']\n# Test the image.\n- name: 'gcr.io/gcp-runtimes/container-structure-test'\n  args: ['test', '--image', 'gcr.io/$PROJECT_ID/image', '--config', 'test_config.yaml']\n\n# Push the image.\nimages: ['gcr.io/$PROJECT_ID/image']\n```\n\n## Running File Tests Without Docker\n\nContainer images can be represented in multiple formats, and the Docker image\nis just one of them. At their core, images are just a series of layers, each\nof which is a tarball, and so can be interacted with without a working Docker\ndaemon. While running command tests currently requires a functioning Docker\ndaemon on the host machine, File Existence/Content tests do not. This can be\nuseful when dealing with images which have been `docker export`ed\nor saved in a different image format than the Docker format, or when you're simply\ntrying to run structure tests in an environment where Docker can't be installed.\n\nTo run tests without using a Docker daemon, users can specify a different\n\"driver\" to use in the tests, with the `--driver` flag.\n\nAn example test run with a different driver looks like:\n```shell\ncontainer-structure-test test --driver tar --image gcr.io/registry/image:latest \\\n--config config.yaml\n```\n\nThe currently supported drivers in the framework are:\n- `docker`: the default driver.\nSupports all tests, and uses the Docker daemon on the host to run them. You can\nset the runtime to use (by example `runsc` to run with gVisor) using `--runtime`\nflag.\n- `tar`: a tar driver, which extracts an image filesystem to wherever tests are\nrunning, and runs file/metadata tests against it.\nDoes *not* support command tests.\n\n\n### Running Structure Tests Through Bazel\nStructure tests can also be run through `bazel`.\n\nWith Bazel 6 and bzlmod, just see https://registry.bazel.build/modules/container_structure_test.\nOtherwise, load the rule and its dependencies in your `WORKSPACE`, see bazel/test/WORKSPACE.bazel in this repo.\n\nLoad the rule definition in your BUILD file and declare a `container_structure_test` target, passing in your image and config file as parameters:\n\n```bazel\nload(\"@container_structure_test//:defs.bzl\", \"container_structure_test\")\n\ncontainer_structure_test(\n    name = \"hello_test\",\n    configs = [\"testdata/hello.yaml\"],\n    image = \":hello\",\n)\n```\n\n### Flags:\n`container-structure-test test -h`\n```\n  -c, --config stringArray             test config files\n      --default-image-tag string       default image tag to used when loading images to the daemon. required when --image-from-oci-layout refers to a oci layout lacking the reference annotation.\n  -d, --driver string                  driver to use when running tests (default \"docker\")\n  -f, --force                          force run of host driver (without user prompt)\n  -h, --help                           help for test\n  -i, --image string                   path to test image\n      --image-from-oci-layout string   path to the oci layout to test against\n      --metadata string                path to image metadata file\n      --no-color                       no color in the output\n  -o, --output string                  output format for the test report (available format: text, json, junit) (default \"text\")\n      --platform string                Set platform if host is multi-platform capable (default \"linux/amd64\")\n      --pull                           force a pull of the image before running tests\n  -q, --quiet                          flag to suppress output\n      --runtime string                 runtime to use with docker driver\n      --save                           preserve created containers after test run\n      --test-report string             generate test report and write it to specified file (supported format: json, junit; default: json)\n ```\nSee this [example repo](https://github.com/nkubala/structure-test-examples) for a full working example.\n\n## Output formats\n\nReports are generated using one of the following output formats: `text`, `json` or `junit`.\nFormats like `json` and `junit` can also be used to write a report to a specified file using the `--test-report`.\n\n### Output samples\n\n#### Text\n\n```text\n====================================\n====== Test file: config.yaml ======\n====================================\n=== RUN: File Existence Test: whoami\n--- PASS\nduration: 0s\n=== RUN: Metadata Test\n--- PASS\nduration: 0s\n\n=====================================\n============== RESULTS ==============\n=====================================\nPasses:      2\nFailures:    0\nDuration:    0s\nTotal tests: 2\n\nPASS\n```\n\n#### JSON\n\nThe following sample has been formatted.\n\n```json\n{\n  \"Pass\": 2,\n  \"Fail\": 0,\n  \"Total\": 2,\n  \"Duration\": 0,\n  \"Results\": [\n    {\n      \"Name\": \"File Existence Test: whoami\",\n      \"Pass\": true,\n      \"Duration\": 0\n    },\n    {\n      \"Name\": \"Metadata Test\",\n      \"Pass\": true,\n      \"Duration\": 0\n    }\n  ]\n}\n```\n\n### JUnit\n\nThe following sample has been formatted.\n\n```xml\n\u003c?xml version=\"1.0\"?\u003e\n\u003ctestsuites failures=\"0\" tests=\"2\" time=\"0\"\u003e\n  \u003ctestsuite\u003e\n    \u003ctestcase name=\"File Existence Test: whoami\" time=\"0\"/\u003e\n    \u003ctestcase name=\"Metadata Test\" time=\"0\"/\u003e\n  \u003c/testsuite\u003e\n\u003c/testsuites\u003e\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgooglecontainertools%2Fcontainer-structure-test","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgooglecontainertools%2Fcontainer-structure-test","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgooglecontainertools%2Fcontainer-structure-test/lists"}