├── testing
└── ansible
│ ├── roles
│ ├── website
│ │ ├── defaults
│ │ │ └── main.yml
│ │ ├── meta
│ │ │ └── main.yml
│ │ ├── tests
│ │ │ ├── playbook.yml
│ │ │ ├── rolecule.yml
│ │ │ └── goss.yaml
│ │ ├── files
│ │ │ └── index.html
│ │ └── tasks
│ │ │ └── main.yml
│ ├── simple
│ │ ├── files
│ │ │ └── test2.txt
│ │ ├── meta
│ │ │ └── main.yml
│ │ ├── templates
│ │ │ └── test1.txt.j2
│ │ ├── defaults
│ │ │ └── main.yml
│ │ ├── tests
│ │ │ ├── playbook.yml
│ │ │ ├── rolecule.yml
│ │ │ └── goss.yaml
│ │ └── tasks
│ │ │ └── main.yml
│ ├── sysctl
│ │ ├── tests
│ │ │ ├── scenarios
│ │ │ │ ├── build
│ │ │ │ │ └── test_all.py
│ │ │ │ └── provision
│ │ │ │ │ └── test_all.py
│ │ │ ├── goss.yaml
│ │ │ ├── playbook.yml
│ │ │ └── rolecule.yml
│ │ ├── defaults
│ │ │ └── main.yml
│ │ └── tasks
│ │ │ └── main.yml
│ └── sshd
│ │ ├── vars
│ │ ├── Debian.yml
│ │ └── RedHat.yml
│ │ ├── meta
│ │ └── main.yml
│ │ ├── tests
│ │ ├── playbook.yml
│ │ ├── goss-build.yaml
│ │ ├── ubuntu
│ │ │ └── playbook.yml
│ │ ├── rolecule.yml
│ │ └── goss.yaml
│ │ ├── handlers
│ │ └── main.yml
│ │ ├── defaults
│ │ └── main.yml
│ │ ├── templates
│ │ └── sshd_config.j2
│ │ └── tasks
│ │ └── main.yml
│ ├── amazonlinux2-systemd.Dockerfile
│ ├── rockylinux-9.1-systemd.Dockerfile
│ ├── ubuntu-22.04-systemd.Dockerfile
│ └── ubuntu-24.04-systemd.Dockerfile
├── .gitignore
├── main.go
├── .mise.toml
├── cmd
├── version.go
├── init.go
├── list.go
├── destroy.go
├── shell.go
├── root.go
├── verify.go
├── exec.go
├── create.go
├── test.go
└── converge.go
├── .github
└── workflows
│ ├── release.yml
│ └── test.yml
├── pkg
├── filesystem
│ └── filesystem.go
├── verifier
│ ├── verifier.go
│ ├── testinfra.go
│ ├── verifier_test.go
│ ├── goss.go
│ ├── testinfra_test.go
│ └── goss_test.go
├── container
│ ├── engine.go
│ ├── engine_test.go
│ ├── podman.go
│ └── docker.go
├── provisioner
│ ├── provisioner_test.go
│ ├── provisioner.go
│ ├── ansible.go
│ ├── ansible_metadata.go
│ └── ansible_test.go
├── command
│ └── command.go
├── actions
│ ├── actions.go
│ └── actions_test.go
├── instance
│ └── instance.go
└── config
│ ├── config_test.go
│ └── config.go
├── .goreleaser.yaml
├── go.mod
├── justfile
├── go.sum
├── README.md
└── LICENSE
/testing/ansible/roles/website/defaults/main.yml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/testing/ansible/roles/simple/files/test2.txt:
--------------------------------------------------------------------------------
1 | test2
2 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sysctl/tests/scenarios/build/test_all.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sysctl/tests/scenarios/provision/test_all.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/vars/Debian.yml:
--------------------------------------------------------------------------------
1 | sshd_service_name: ssh
2 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/vars/RedHat.yml:
--------------------------------------------------------------------------------
1 | sshd_service_name: sshd
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | dist/
2 | .idea/
3 | .vscode/
4 | rolecule
5 | rolecule.exe
6 |
--------------------------------------------------------------------------------
/testing/ansible/roles/simple/meta/main.yml:
--------------------------------------------------------------------------------
1 | dependencies:
2 | - role: sshd
3 |
--------------------------------------------------------------------------------
/testing/ansible/roles/simple/templates/test1.txt.j2:
--------------------------------------------------------------------------------
1 | {{ simple_template_value }}
2 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/meta/main.yml:
--------------------------------------------------------------------------------
1 | dependencies:
2 | - role: sysctl
3 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sysctl/defaults/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | ansible_swappiness: 15
3 |
--------------------------------------------------------------------------------
/testing/ansible/roles/simple/defaults/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | simple_template_value: test1
3 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sysctl/tests/goss.yaml:
--------------------------------------------------------------------------------
1 | kernel-param:
2 | vm.swappiness:
3 | value: '15'
4 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/tests/playbook.yml:
--------------------------------------------------------------------------------
1 | - name: test
2 | hosts: localhost
3 | roles:
4 | - sshd
5 |
--------------------------------------------------------------------------------
/testing/ansible/roles/simple/tests/playbook.yml:
--------------------------------------------------------------------------------
1 | - name: test
2 | hosts: localhost
3 | roles:
4 | - simple
5 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sysctl/tests/playbook.yml:
--------------------------------------------------------------------------------
1 | - name: test
2 | hosts: localhost
3 | roles:
4 | - sysctl
5 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "github.com/z0mbix/rolecule/cmd"
4 |
5 | func main() {
6 | cmd.Execute()
7 | }
8 |
--------------------------------------------------------------------------------
/testing/ansible/roles/website/meta/main.yml:
--------------------------------------------------------------------------------
1 | dependencies:
2 | - role: geerlingguy.nginx
3 | - role: geerlingguy.redis
4 | - role: simple
5 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/tests/goss-build.yaml:
--------------------------------------------------------------------------------
1 | package:
2 | openssh-server:
3 | installed: true
4 | user:
5 | sshd:
6 | exists: true
7 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/handlers/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: reload sshd
3 | ansible.builtin.systemd:
4 | name: "{{ sshd_service_name }}.service"
5 | state: reloaded
6 |
--------------------------------------------------------------------------------
/testing/ansible/roles/website/tests/playbook.yml:
--------------------------------------------------------------------------------
1 | - name: test
2 | hosts: localhost
3 | pre_tasks:
4 | - name: update apt cache
5 | ansible.builtin.apt:
6 | update_cache: yes
7 | roles:
8 | - website
9 |
--------------------------------------------------------------------------------
/testing/ansible/roles/website/files/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Home page
4 |
5 |
6 | Welcome!
7 | Hello visitor
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.mise.toml:
--------------------------------------------------------------------------------
1 | [env]
2 | mise.path = ["./bin"]
3 | GO_VERSION = "{{exec(command='grep \"^go 1\\.[0-9]\\+\\.[0-9]\\+$\" go.mod | cut -f2 -d\" \"')}}"
4 |
5 | [tools]
6 | golang = "{{exec(command='grep \"^go 1\\.[0-9]\\+\\.[0-9]\\+$\" go.mod | cut -f2 -d\" \"')}}"
7 |
--------------------------------------------------------------------------------
/testing/ansible/roles/website/tasks/main.yml:
--------------------------------------------------------------------------------
1 | - name: output the hostname
2 | ansible.builtin.debug:
3 | msg: "hostname is {{ ansible_hostname }}"
4 |
5 | - name: install index.html
6 | ansible.builtin.copy:
7 | src: index.html
8 | dest: /var/www/html/index.html
9 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/defaults/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | sshd_port: 22
3 | sshd_address_family: any
4 | sshd_listen_address: "0.0.0.0"
5 | sshd_syslog_facility: AUTH
6 | sshd_log_level: INFO
7 | sshd_sftd_server_enabled: yes
8 | sshd_service_name: sshd
9 | sshd_enabled: yes
10 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/tests/ubuntu/playbook.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: update apt cache
3 | hosts: localhost
4 | tasks:
5 | - name: update apt cache
6 | ansible.builtin.apt:
7 | update_cache: yes
8 | tags:
9 | - always
10 |
11 | - name: test
12 | hosts: localhost
13 | roles:
14 | - sshd
15 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sysctl/tasks/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: manage swappiness
3 | ansible.builtin.sysctl:
4 | name: vm.swappiness
5 | value: "{{ ansible_swappiness }}"
6 | state: present
7 | tags:
8 | - provision
9 |
10 | - name: output swappiness
11 | ansible.builtin.debug:
12 | msg: "vm.swappiness is {{ ansible_swappiness }}"
13 |
--------------------------------------------------------------------------------
/testing/ansible/roles/website/tests/rolecule.yml:
--------------------------------------------------------------------------------
1 | ---
2 | provisioner:
3 | name: ansible
4 | extra_args:
5 | - --diff
6 | - --verbose
7 | env:
8 | ANSIBLE_NOCOLOR: False
9 |
10 | verifier:
11 | name: goss
12 | extra_args:
13 | - --format
14 | - tap
15 |
16 | instances:
17 | - name: ubuntu-24.04
18 | image: ubuntu-systemd:24.04
19 |
--------------------------------------------------------------------------------
/testing/ansible/roles/simple/tests/rolecule.yml:
--------------------------------------------------------------------------------
1 | engine:
2 | name: docker
3 |
4 | provisioner:
5 | name: ansible
6 | extra_args:
7 | - --diff
8 | env:
9 | ANSIBLE_NOCOLOR: False
10 |
11 | verifier:
12 | name: goss
13 | extra_args:
14 | - --format
15 | - tap
16 |
17 | instances:
18 | - name: ubuntu-24.04
19 | image: ubuntu-systemd:24.04
20 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sysctl/tests/rolecule.yml:
--------------------------------------------------------------------------------
1 | engine:
2 | name: docker
3 |
4 | provisioner:
5 | name: ansible
6 | extra_args:
7 | - --diff
8 | - --verbose
9 | env:
10 | ANSIBLE_NOCOLOR: False
11 |
12 | verifier:
13 | name: goss
14 | extra_args:
15 | - --format
16 | - tap
17 |
18 | instances:
19 | - name: ubuntu-24.04
20 | image: ubuntu-systemd:24.04
21 |
--------------------------------------------------------------------------------
/testing/ansible/roles/website/tests/goss.yaml:
--------------------------------------------------------------------------------
1 | file:
2 | /var/www/html/index.html:
3 | exists: true
4 | mode: "0644"
5 | owner: root
6 | group: root
7 | filetype: file
8 | contents: |
9 |
10 |
11 | Home page
12 |
13 |
14 | Welcome!
15 | Hello visitor
16 |
17 |
18 |
--------------------------------------------------------------------------------
/cmd/version.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/spf13/cobra"
7 | "github.com/z0mbix/rolecule/pkg/config"
8 | )
9 |
10 | func init() {
11 | rootCmd.AddCommand(versionCmd)
12 | }
13 |
14 | var version string = "dev"
15 |
16 | var versionCmd = &cobra.Command{
17 | Use: "version",
18 | Short: "Show version",
19 | Run: func(cmd *cobra.Command, args []string) {
20 | fmt.Printf("%s %s\n", config.AppName, version)
21 | },
22 | }
23 |
--------------------------------------------------------------------------------
/testing/ansible/amazonlinux2-systemd.Dockerfile:
--------------------------------------------------------------------------------
1 | FROM docker.io/amazonlinux:2
2 |
3 | RUN yum install -y curl procps-ng systemd python3 python3-pip util-linux && \
4 | python3 -m pip install ansible ansible-core
5 |
6 | # # Install goss (https://github.com/goss-org/goss)
7 | RUN curl -sSL https://github.com/goss-org/goss/releases/latest/download/goss-linux-amd64 -o /usr/local/bin/goss && \
8 | chmod +rx /usr/local/bin/goss
9 |
10 | # VOLUME [ "/sys/fs/cgroup" ]
11 | CMD ["/sbin/init"]
12 |
--------------------------------------------------------------------------------
/testing/ansible/roles/simple/tests/goss.yaml:
--------------------------------------------------------------------------------
1 | file:
2 | /tmp/simple-directory:
3 | exists: true
4 | mode: "0750"
5 | owner: root
6 | group: root
7 | filetype: directory
8 | /tmp/test1.txt:
9 | exists: true
10 | mode: "0644"
11 | owner: root
12 | group: root
13 | filetype: file
14 | contents:
15 | - "test1"
16 | /tmp/test2.txt:
17 | exists: true
18 | mode: "0640"
19 | owner: root
20 | group: root
21 | filetype: file
22 | contents:
23 | - "test2"
24 | package:
25 | git:
26 | installed: true
27 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/templates/sshd_config.j2:
--------------------------------------------------------------------------------
1 | # To modify the system-wide sshd configuration, create a *.conf file under
2 | # /etc/ssh/sshd_config.d/ which will be automatically included below
3 | Include /etc/ssh/sshd_config.d/*.conf
4 |
5 | Port {{ sshd_port }}
6 | AddressFamily {{ sshd_address_family }}
7 | ListenAddress {{ sshd_listen_address }}
8 |
9 | # Logging
10 | SyslogFacility {{ sshd_syslog_facility }}
11 | LogLevel {{ sshd_log_level }}
12 |
13 | # Authentication:
14 | PermitRootLogin no
15 | PubkeyAuthentication yes
16 | AuthorizedKeysFile .ssh/authorized_keys
17 |
18 | {% if sshd_sftd_server_enabled %}
19 | Subsystem sftp /usr/libexec/openssh/sftp-server
20 | {% endif %}
21 |
--------------------------------------------------------------------------------
/cmd/init.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "github.com/apex/log"
5 | "github.com/spf13/cobra"
6 | "github.com/z0mbix/rolecule/pkg/config"
7 | )
8 |
9 | var (
10 | engineName string
11 | )
12 |
13 | func init() {
14 | rootCmd.AddCommand(initCmd)
15 | initCmd.Flags().StringVarP(&engineName, "engine", "e", "docker", "Specify the container engine to use (docker or podman)")
16 | }
17 |
18 | var initCmd = &cobra.Command{
19 | Use: "init",
20 | Short: "Initialise the project with a tests directory and a rolecule.yml file",
21 | Run: func(cmd *cobra.Command, args []string) {
22 | err := config.Create(engineName)
23 | if err != nil {
24 | log.Fatal(err.Error())
25 | }
26 | },
27 | }
28 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Release
2 | run-name: Release ${{ github.ref_name }} triggered by @${{ github.actor }}
3 |
4 | on:
5 | push:
6 | tags:
7 | - "v*"
8 |
9 | permissions:
10 | contents: write
11 |
12 | jobs:
13 | goreleaser:
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: actions/checkout@v4
17 | with:
18 | fetch-depth: 0
19 |
20 | - uses: actions/setup-go@v5
21 | with:
22 | go-version-file: "go.mod"
23 | cache: true
24 |
25 | - name: goreleaser
26 | uses: goreleaser/goreleaser-action@v6
27 | with:
28 | args: release --clean
29 | env:
30 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
31 |
--------------------------------------------------------------------------------
/testing/ansible/roles/simple/tasks/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: package
3 | ansible.builtin.package:
4 | name: git
5 | tags:
6 | - build
7 |
8 | - name: template
9 | ansible.builtin.template:
10 | src: test1.txt.j2
11 | dest: /tmp/test1.txt
12 | owner: root
13 | group: root
14 | mode: 0644
15 | tags:
16 | - provision
17 |
18 | - name: file
19 | ansible.builtin.copy:
20 | src: test2.txt
21 | dest: /tmp/test2.txt
22 | owner: root
23 | group: root
24 | mode: 0640
25 | tags:
26 | - provision
27 |
28 | - name: directory
29 | ansible.builtin.file:
30 | path: /tmp/simple-directory
31 | state: directory
32 | owner: root
33 | group: root
34 | mode: 0750
35 | tags:
36 | - provision
37 |
--------------------------------------------------------------------------------
/pkg/filesystem/filesystem.go:
--------------------------------------------------------------------------------
1 | package filesystem
2 |
3 | import (
4 | "os"
5 | "os/exec"
6 | )
7 |
8 | // CommandExists looks for a command in the PATH
9 | func CommandExists(command string) bool {
10 | _, err := exec.LookPath(command)
11 | return err == nil
12 | }
13 |
14 | // FileExists checks if a file exists
15 | func FileExists(path string) bool {
16 | if stat, err := os.Stat(path); !os.IsNotExist(err) && !stat.IsDir() {
17 | return true
18 | }
19 | return false
20 | }
21 |
22 | // ReadFile reads the entire file at path and returns its contents
23 | func ReadFile(path string) ([]byte, error) {
24 | return os.ReadFile(path)
25 | }
26 |
27 | // GetCurrentDir returns the current working directory
28 | func GetCurrentDir() (string, error) {
29 | return os.Getwd()
30 | }
31 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/tasks/main.yml:
--------------------------------------------------------------------------------
1 | - name: Include OS-specific variables
2 | ansible.builtin.include_vars: "{{ ansible_os_family }}.yml"
3 | tags:
4 | - always
5 |
6 | - name: package
7 | ansible.builtin.package:
8 | name: openssh-server
9 | tags:
10 | - build
11 |
12 | - name: configure
13 | ansible.builtin.template:
14 | src: sshd_config.j2
15 | dest: /etc/ssh/sshd_config
16 | owner: root
17 | group: root
18 | mode: 0600
19 | notify:
20 | - reload sshd
21 | tags:
22 | - provision
23 |
24 | - name: service
25 | ansible.builtin.systemd:
26 | name: "{{ sshd_service_name }}.service"
27 | state: "{{ 'started' if sshd_enabled else 'stopped' }}"
28 | enabled: "{{ sshd_enabled }}"
29 | tags:
30 | - provision
31 |
--------------------------------------------------------------------------------
/pkg/verifier/verifier.go:
--------------------------------------------------------------------------------
1 | package verifier
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type Config struct {
8 | Name string `mapstructure:"name"`
9 | TestFile string `mapstructure:"testfile"`
10 | ExtraArgs []string `mapstructure:"extra_args"`
11 | }
12 |
13 | type Verifier interface {
14 | GetCommand() (map[string]string, string, []string)
15 | GetTestFile() string
16 | WithTestFile(file string) Verifier
17 | String() string
18 | }
19 |
20 | func NewVerifier(config Config) (Verifier, error) {
21 | if config.Name == "goss" {
22 | return getGossConfig(config), nil
23 | }
24 |
25 | if config.Name == "testinfra" {
26 | return defaultTestInfraConfig, nil
27 | }
28 |
29 | return nil, fmt.Errorf("Verifier '%s' not recognised (only goss is currently supported)", config.Name)
30 | }
31 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/tests/rolecule.yml:
--------------------------------------------------------------------------------
1 | engine:
2 | name: docker
3 |
4 | provisioner:
5 | name: ansible
6 | extra_args:
7 | - --diff
8 | env:
9 | ANSIBLE_NOCOLOR: False
10 |
11 | verifier:
12 | name: goss
13 | extra_args:
14 | - --format
15 | - tap
16 |
17 | instances:
18 | - name: ubuntu-22.04
19 | image: ubuntu-systemd:22.04
20 | playbook: ubuntu/playbook.yml
21 |
22 | - name: ubuntu-22.04-build
23 | image: ubuntu-systemd:22.04
24 | playbook: ubuntu/playbook.yml
25 | testfile: goss-build.yaml
26 | tags:
27 | - build
28 |
29 | - name: rockylinux-9.1
30 | image: rockylinux-systemd:9.1
31 |
32 | - name: rockylinux-9.1-build
33 | image: rockylinux-systemd:9.1
34 | testfile: goss-build.yaml
35 | tags:
36 | - build
37 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 | run-name: Test ${{ github.ref_name }} triggered by @${{ github.actor }}
3 |
4 | on:
5 | push:
6 | branches:
7 | - main
8 | pull_request:
9 |
10 | jobs:
11 | test-linux:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - uses: actions/checkout@v4
15 |
16 | - name: Set up go
17 | uses: actions/setup-go@v5
18 | with:
19 | go-version-file: go.mod
20 |
21 | - name: Test
22 | run: go test -v ./... -coverprofile=cover.out
23 |
24 | test-windows:
25 | runs-on: windows-latest
26 | steps:
27 | - uses: actions/checkout@v4
28 |
29 | - name: Set up Go
30 | uses: actions/setup-go@v5
31 | with:
32 | go-version-file: go.mod
33 |
34 | - name: Test
35 | run: go test -v ./... -coverprofile=cover.out
36 |
--------------------------------------------------------------------------------
/cmd/list.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/apex/log"
7 | "github.com/spf13/cobra"
8 | "github.com/z0mbix/rolecule/pkg/config"
9 | )
10 |
11 | func init() {
12 | rootCmd.AddCommand(listCmd)
13 | }
14 |
15 | var listCmd = &cobra.Command{
16 | Use: "list",
17 | Aliases: []string{"l", "ls"},
18 | Short: "List the running containers for this role/module/recipe",
19 | Run: func(cmd *cobra.Command, args []string) {
20 | cfg, err := config.Get()
21 | if err != nil {
22 | log.Fatal(err.Error())
23 | }
24 |
25 | fmt.Println(list(cfg))
26 | },
27 | }
28 |
29 | func list(cfg *config.Config) string {
30 | namePrefix := fmt.Sprintf("%s-%s", config.AppName, cfg.RoleName)
31 | output, err := cfg.Engine.List(namePrefix)
32 | if err != nil {
33 | return ""
34 | }
35 |
36 | return output
37 | }
38 |
--------------------------------------------------------------------------------
/testing/ansible/rockylinux-9.1-systemd.Dockerfile:
--------------------------------------------------------------------------------
1 | FROM rockylinux/rockylinux:9.1
2 |
3 | RUN dnf install -y systemd systemd-libs util-linux ansible-core procps-ng vim-enhanced && \
4 | rm -f /lib/systemd/system/multi-user.target.wants/*;\
5 | rm -f /etc/systemd/system/*.wants/*;\
6 | rm -f /lib/systemd/system/local-fs.target.wants/*; \
7 | rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
8 | rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
9 | rm -f /lib/systemd/system/basic.target.wants/*;\
10 | rm -f /lib/systemd/system/anaconda.target.wants/*;
11 |
12 | # Install goss (https://github.com/goss-org/goss)
13 | RUN curl -sSL https://github.com/goss-org/goss/releases/latest/download/goss-linux-amd64 -o /usr/local/bin/goss && \
14 | chmod +rx /usr/local/bin/goss
15 |
16 | VOLUME [ "/sys/fs/cgroup" ]
17 | CMD ["/usr/sbin/init"]
18 |
--------------------------------------------------------------------------------
/cmd/destroy.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "github.com/apex/log"
5 | "github.com/spf13/cobra"
6 | "github.com/z0mbix/rolecule/pkg/config"
7 | )
8 |
9 | func init() {
10 | rootCmd.AddCommand(destroyCmd)
11 | }
12 |
13 | var destroyCmd = &cobra.Command{
14 | Use: "destroy",
15 | Aliases: []string{"rm"},
16 | Short: "Destroy everything",
17 | Run: func(cmd *cobra.Command, args []string) {
18 | cfg, err := config.Get()
19 | if err != nil {
20 | log.Fatal(err.Error())
21 | }
22 |
23 | err = destroy(cfg)
24 | if err != nil {
25 | log.Fatal(err.Error())
26 | }
27 | },
28 | }
29 |
30 | func destroy(cfg *config.Config) error {
31 | for _, instance := range cfg.Instances {
32 | log.Infof("destroying container %s", instance.Name)
33 | err := instance.Destroy()
34 | if err != nil {
35 | return err
36 | }
37 | }
38 |
39 | return nil
40 | }
41 |
--------------------------------------------------------------------------------
/pkg/container/engine.go:
--------------------------------------------------------------------------------
1 | package container
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type Engine interface {
8 | Exec(string, map[string]string, string, []string) error
9 | Exists(string) bool
10 | List(string) (string, error)
11 | Remove(string) error
12 | Run(string, []string) (string, error)
13 | Shell(string) error
14 | String() string
15 | }
16 |
17 | type EngineConfig struct {
18 | Name string `mapstructure:"name"`
19 | }
20 |
21 | func NewEngine(name string) (Engine, error) {
22 | switch name {
23 | case "docker":
24 | return &DockerEngine{
25 | Name: "docker",
26 | Socket: "docker://",
27 | }, nil
28 | case "podman":
29 | return &PodmanEngine{
30 | Name: "podman",
31 | Socket: "podman://",
32 | }, nil
33 | default:
34 | return nil, fmt.Errorf("container engine '%s' not recognised (docker and podman currently supported)", name)
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/testing/ansible/roles/sshd/tests/goss.yaml:
--------------------------------------------------------------------------------
1 | package:
2 | openssh-server:
3 | installed: true
4 | user:
5 | sshd:
6 | exists: true
7 | file:
8 | /etc/ssh/sshd_config:
9 | exists: true
10 | mode: "0600"
11 | owner: root
12 | group: root
13 | filetype: file
14 | contents:
15 | - "Port 22"
16 | - "AddressFamily any"
17 | - "ListenAddress 0.0.0.0"
18 | - "SyslogFacility AUTH"
19 | - "LogLevel INFO"
20 | - "PermitRootLogin no"
21 | - "PubkeyAuthentication yes"
22 | - "/AuthorizedKeysFile\\s.ssh/authorized_keys/"
23 | - "Subsystem sftp /usr/libexec/openssh/sftp-server"
24 | - "!/PermitRootLogin[[:space:]].*yes/"
25 | service:
26 | sshd:
27 | enabled: true
28 | running: true
29 | process:
30 | sshd:
31 | running: true
32 | port:
33 | tcp:22:
34 | listening: true
35 | ip:
36 | - 0.0.0.0
37 |
--------------------------------------------------------------------------------
/pkg/verifier/testinfra.go:
--------------------------------------------------------------------------------
1 | package verifier
2 |
3 | type TestInfraVerifier struct {
4 | Name string
5 | Command string
6 | Args []string
7 | EnvVars map[string]string
8 | TestFile string
9 | }
10 |
11 | func (v TestInfraVerifier) String() string {
12 | return v.Name
13 | }
14 |
15 | func (v TestInfraVerifier) WithTestFile(file string) Verifier {
16 | v.TestFile = file
17 | return v
18 | }
19 |
20 | func (v TestInfraVerifier) GetCommand() (map[string]string, string, []string) {
21 | return v.EnvVars, v.Command, v.Args
22 | }
23 |
24 | func (v TestInfraVerifier) GetTestFile() string {
25 | return v.TestFile
26 | }
27 |
28 | // TODO: how to get socket and container name?
29 | var defaultTestInfraConfig = TestInfraVerifier{
30 | Name: "testinfra",
31 | Command: "py.test",
32 | Args: []string{
33 | "-vv",
34 | "--hosts",
35 | "podman://foobar",
36 | },
37 | TestFile: "test.py",
38 | }
39 |
--------------------------------------------------------------------------------
/cmd/shell.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "github.com/apex/log"
5 | "github.com/spf13/cobra"
6 | "github.com/z0mbix/rolecule/pkg/actions"
7 | "github.com/z0mbix/rolecule/pkg/config"
8 | )
9 |
10 | var shellContainerName string
11 |
12 | func init() {
13 | rootCmd.AddCommand(shellCmd)
14 | shellCmd.Flags().StringVarP(&shellContainerName, "name", "n", "", "Login to a specific container")
15 | }
16 |
17 | var shellCmd = &cobra.Command{
18 | Use: "shell",
19 | Aliases: []string{"sh", "login"},
20 | Short: "Open a shell in a container",
21 | Example: ` rolecule shell
22 | rolecule shell -n rolecule-sshd-ubuntu-22.04`,
23 | Run: func(cmd *cobra.Command, args []string) {
24 | cfg, err := config.Get()
25 | if err != nil {
26 | log.Fatal(err.Error())
27 | }
28 |
29 | err = actions.Shell(cfg.Instances, shellContainerName)
30 | if err != nil {
31 | log.Fatal(err.Error())
32 | }
33 | },
34 | }
35 |
--------------------------------------------------------------------------------
/cmd/root.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "os"
5 |
6 | "github.com/apex/log"
7 | "github.com/apex/log/handlers/cli"
8 | "github.com/spf13/cobra"
9 | )
10 |
11 | var debugLoggingEnabled bool
12 |
13 | func init() {
14 | rootCmd.PersistentFlags().BoolVarP(&debugLoggingEnabled, "debug", "d", false, "enable debug output")
15 | }
16 |
17 | var rootCmd = &cobra.Command{
18 | Use: "rolecule",
19 | Short: "rolecule helps you test your ansible roles",
20 | Long: `rolecule uses docker or podman to test your
21 | ansible roles in a systemd enabled container,
22 | then tests them with a verifier (goss).`,
23 |
24 | PersistentPreRun: func(cmd *cobra.Command, args []string) {
25 | log.SetHandler(cli.New(os.Stderr))
26 |
27 | if debugLoggingEnabled {
28 | log.SetLevel(log.DebugLevel)
29 | }
30 | },
31 | }
32 |
33 | func Execute() {
34 | err := rootCmd.Execute()
35 | if err != nil {
36 | os.Exit(1)
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/cmd/verify.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "github.com/apex/log"
5 | "github.com/spf13/cobra"
6 | "github.com/z0mbix/rolecule/pkg/config"
7 | )
8 |
9 | func init() {
10 | rootCmd.AddCommand(verifyCmd)
11 | }
12 |
13 | var verifyCmd = &cobra.Command{
14 | Use: "verify",
15 | Aliases: []string{"v"},
16 | Short: "Verify your containers are configured how you expect",
17 | Run: func(cmd *cobra.Command, args []string) {
18 | cfg, err := config.Get()
19 | if err != nil {
20 | log.Fatal(err.Error())
21 | }
22 |
23 | err = verify(cfg)
24 | if err != nil {
25 | log.Fatal(err.Error())
26 | }
27 | },
28 | }
29 |
30 | func verify(cfg *config.Config) error {
31 | for _, instance := range cfg.Instances {
32 | log.Infof("verifying container %s with %s (%s)", instance.Name, instance.Verifier, instance.Verifier.GetTestFile())
33 | if err := instance.Verify(); err != nil {
34 | return err
35 | }
36 | }
37 |
38 | return nil
39 | }
40 |
--------------------------------------------------------------------------------
/pkg/container/engine_test.go:
--------------------------------------------------------------------------------
1 | package container
2 |
3 | import (
4 | "reflect"
5 | "testing"
6 | )
7 |
8 | func TestNewEngine(t *testing.T) {
9 | type args struct {
10 | name string
11 | }
12 | tests := []struct {
13 | name string
14 | args args
15 | want Engine
16 | wantErr bool
17 | }{
18 | {
19 | name: "docker",
20 | args: args{
21 | name: "docker",
22 | },
23 | want: &DockerEngine{
24 | Name: "docker",
25 | Socket: "docker://",
26 | },
27 | },
28 | {
29 | name: "podman",
30 | args: args{
31 | name: "podman",
32 | },
33 | want: &PodmanEngine{
34 | Name: "podman",
35 | Socket: "podman://",
36 | },
37 | },
38 | }
39 | for _, tt := range tests {
40 | t.Run(tt.name, func(t *testing.T) {
41 | got, err := NewEngine(tt.args.name)
42 | if (err != nil) != tt.wantErr {
43 | t.Errorf("NewEngine() error = %v, wantErr %v", err, tt.wantErr)
44 | return
45 | }
46 | if !reflect.DeepEqual(got, tt.want) {
47 | t.Errorf("NewEngine() got = %v, want %v", got, tt.want)
48 | }
49 | })
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/cmd/exec.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "github.com/apex/log"
5 | "github.com/spf13/cobra"
6 | "github.com/z0mbix/rolecule/pkg/actions"
7 | "github.com/z0mbix/rolecule/pkg/config"
8 | )
9 |
10 | var execContainerName string
11 |
12 | func init() {
13 | rootCmd.AddCommand(execCmd)
14 | execCmd.Flags().StringVarP(&execContainerName, "name", "n", "", "Execute command in a specific container")
15 | }
16 |
17 | var execCmd = &cobra.Command{
18 | Use: "exec [command]",
19 | Aliases: []string{"e", "execute"},
20 | Short: "Execute a command in a container",
21 | Long: `Execute a command in a running container without opening an interactive shell.
22 |
23 | Example:
24 | rolecule exec systemctl status
25 | rolecule exec -n rolecule-sshd-ubuntu-22.04 apt-get -y update`,
26 | Args: cobra.MinimumNArgs(1),
27 | Run: func(cmd *cobra.Command, args []string) {
28 | cfg, err := config.Get()
29 | if err != nil {
30 | log.Fatal(err.Error())
31 | }
32 |
33 | err = actions.Exec(cfg.Instances, execContainerName, args[0], args[1:])
34 | if err != nil {
35 | log.Fatal(err.Error())
36 | }
37 | },
38 | }
39 |
--------------------------------------------------------------------------------
/pkg/provisioner/provisioner_test.go:
--------------------------------------------------------------------------------
1 | package provisioner
2 |
3 | import (
4 | "reflect"
5 | "testing"
6 | )
7 |
8 | func TestNewProvisioner(t *testing.T) {
9 | type args struct {
10 | config Config
11 | }
12 | tests := []struct {
13 | name string
14 | args args
15 | want Provisioner
16 | wantErr bool
17 | }{
18 | {
19 | name: "ansible",
20 | args: args{
21 | config: Config{
22 | Name: "ansible",
23 | },
24 | },
25 | want: defaultAnsibleConfig,
26 | wantErr: false,
27 | },
28 | {
29 | name: "puppet",
30 | args: args{
31 | config: Config{
32 | Name: "puppet",
33 | },
34 | },
35 | want: nil,
36 | wantErr: true,
37 | },
38 | }
39 | for _, tt := range tests {
40 | t.Run(tt.name, func(t *testing.T) {
41 | got, err := NewProvisioner(tt.args.config)
42 | if (err != nil) != tt.wantErr {
43 | t.Errorf("NewProvisioner() error = %v, wantErr %v", err, tt.wantErr)
44 | return
45 | }
46 | if !reflect.DeepEqual(got, tt.want) {
47 | t.Errorf("NewProvisioner() = %v, want %v", got, tt.want)
48 | }
49 | })
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/cmd/create.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "os"
5 |
6 | "github.com/apex/log"
7 | "github.com/spf13/cobra"
8 | "github.com/z0mbix/rolecule/pkg/config"
9 | )
10 |
11 | func init() {
12 | rootCmd.AddCommand(createCmd)
13 | }
14 |
15 | var createCmd = &cobra.Command{
16 | Use: "create",
17 | Aliases: []string{"cr"},
18 | Short: "Create a new container(s) to test the role in",
19 | Run: func(cmd *cobra.Command, args []string) {
20 | cfg, err := config.Get()
21 | if err != nil {
22 | log.Fatal(err.Error())
23 | }
24 |
25 | err = create(cfg)
26 | if err != nil {
27 | log.Fatal(err.Error())
28 | }
29 | },
30 | }
31 |
32 | func create(cfg *config.Config) error {
33 | for _, instance := range cfg.Instances {
34 | if instance.Engine.Exists(instance.Name) {
35 | log.Infof("container %s already exists!", instance.Name)
36 | continue
37 | }
38 |
39 | log.Infof("creating container %s with %s", instance.Name, instance.Engine)
40 | output, err := instance.Create()
41 | if err != nil {
42 | log.Error(err.Error())
43 | os.Exit(1)
44 | }
45 | log.Debug(output)
46 | }
47 |
48 | return nil
49 | }
50 |
--------------------------------------------------------------------------------
/.goreleaser.yaml:
--------------------------------------------------------------------------------
1 | version: 2
2 | builds:
3 | - env:
4 | - CGO_ENABLED=0
5 | mod_timestamp: "{{ .CommitTimestamp }}"
6 | flags:
7 | - -trimpath
8 | ldflags:
9 | "-s -w -X github.com/z0mbix/rolecule/cmd.version={{.Version}}"
10 | goos:
11 | - darwin
12 | - linux
13 | - windows
14 | goarch:
15 | - amd64
16 | - arm64
17 | goarm:
18 | - "7"
19 | ignore:
20 | - goos: darwin
21 | goarch: "386"
22 | - goos: windows
23 | goarch: "arm"
24 | binary: "{{ .ProjectName }}"
25 | nfpms:
26 | - vendor: z0mbix
27 | homepage: https://github.com/z0mbix/rolecule
28 | maintainer: z0mbix
29 | description: |-
30 | Rolecule is a small, simple tool to test your ansible roles
31 | license: GPL-3.0 license
32 | formats:
33 | - apk
34 | - deb
35 | - rpm
36 | archives:
37 | - id: "zip"
38 | format: zip
39 | - id: "tarball"
40 | format: tar.gz
41 | checksum:
42 | name_template: "{{ .ProjectName }}_{{ .Version }}_SHA256SUMS"
43 | algorithm: sha256
44 | changelog:
45 | use: github-native
46 | gomod:
47 | proxy: true
48 |
--------------------------------------------------------------------------------
/pkg/provisioner/provisioner.go:
--------------------------------------------------------------------------------
1 | package provisioner
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type Provisioner interface {
8 | GetInstallDependenciesCommand() (map[string]string, string, []string)
9 | GetCommand() (map[string]string, string, []string)
10 | WithSkipTags([]string) Provisioner
11 | WithTags([]string) Provisioner
12 | WithPlaybook(string) Provisioner
13 | GetDependencies() Dependencies
14 | WithLocalDependencies([]string) Provisioner
15 | WithGalaxyDependencies([]string) Provisioner
16 | String() string
17 | }
18 |
19 | type Config struct {
20 | Name string `mapstructure:"name"`
21 | Command string `mapstructure:"command"`
22 | Args []string `mapstructure:"args"`
23 | ExtraArgs []string `mapstructure:"extra_args"`
24 | EnvVars map[string]string `mapstructure:"env"`
25 | Playbook string `mapstructure:"playbook"`
26 | }
27 |
28 | func NewProvisioner(config Config) (Provisioner, error) {
29 | if config.Name == "ansible" {
30 | return getAnsibleConfig(config), nil
31 | }
32 |
33 | return nil, fmt.Errorf("provisioner '%s' not recognised", config.Name)
34 | }
35 |
36 | var testDirectory = "tests"
37 |
--------------------------------------------------------------------------------
/cmd/test.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "github.com/apex/log"
5 | "github.com/spf13/cobra"
6 | "github.com/z0mbix/rolecule/pkg/config"
7 | )
8 |
9 | var noDestroy bool
10 |
11 | func init() {
12 | testCmd.Flags().BoolVarP(&noDestroy, "no-destroy", "n", false, "don't destroy containers after completion")
13 | rootCmd.AddCommand(testCmd)
14 | }
15 |
16 | var testCmd = &cobra.Command{
17 | Use: "test",
18 | Aliases: []string{"t"},
19 | Short: "Create the container(s), converge them, and test them",
20 | Long: `"test" will create the containers defined, run the provisioner of choice
21 | against them, test them with your verifier of choice, then destroy everything.`,
22 |
23 | Run: func(cmd *cobra.Command, args []string) {
24 | cfg, err := config.Get()
25 | if err != nil {
26 | log.Fatal(err.Error())
27 | }
28 |
29 | err = create(cfg)
30 | if err != nil {
31 | log.Fatal(err.Error())
32 | }
33 |
34 | err = converge(cfg)
35 | if err != nil {
36 | log.Fatal(err.Error())
37 | }
38 |
39 | err = verify(cfg)
40 | if err != nil {
41 | log.Fatal(err.Error())
42 | }
43 |
44 | if !noDestroy {
45 | if err = destroy(cfg); err != nil {
46 | log.Fatal(err.Error())
47 | }
48 | }
49 |
50 | log.Info("complete")
51 | },
52 | }
53 |
--------------------------------------------------------------------------------
/pkg/verifier/verifier_test.go:
--------------------------------------------------------------------------------
1 | package verifier
2 |
3 | import (
4 | "reflect"
5 | "testing"
6 | )
7 |
8 | func TestNewVerifier(t *testing.T) {
9 | type args struct {
10 | config Config
11 | }
12 | tests := []struct {
13 | name string
14 | args args
15 | want Verifier
16 | wantErr bool
17 | }{
18 | {
19 | name: "goss",
20 | args: args{
21 | config: Config{
22 | Name: "goss",
23 | },
24 | },
25 | want: defaultGossConfig,
26 | wantErr: false,
27 | },
28 | {
29 | name: "testinfra",
30 | args: args{
31 | config: Config{
32 | Name: "testinfra",
33 | },
34 | },
35 | want: defaultTestInfraConfig,
36 | wantErr: false,
37 | },
38 | {
39 | name: "inspec",
40 | args: args{
41 | config: Config{
42 | Name: "inspec",
43 | },
44 | },
45 | want: nil,
46 | wantErr: true,
47 | },
48 | }
49 | for _, tt := range tests {
50 | t.Run(tt.name, func(t *testing.T) {
51 | got, err := NewVerifier(tt.args.config)
52 | if (err != nil) != tt.wantErr {
53 | t.Errorf("NewVerifier() error = %v, wantErr %v", err, tt.wantErr)
54 | return
55 | }
56 | if !reflect.DeepEqual(got, tt.want) {
57 | t.Errorf("NewVerifier() = %v, want %v", got, tt.want)
58 | }
59 | })
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/z0mbix/rolecule
2 |
3 | go 1.24.2
4 |
5 | require (
6 | github.com/apex/log v1.9.0
7 | github.com/spf13/afero v1.14.0
8 | github.com/spf13/cobra v1.9.1
9 | github.com/spf13/viper v1.20.1
10 | github.com/stretchr/testify v1.10.0
11 | github.com/tj/assert v0.0.3
12 | golang.org/x/exp v0.0.0-20250305212735-054e65f0b394
13 | gopkg.in/yaml.v3 v3.0.1
14 | )
15 |
16 | require (
17 | github.com/davecgh/go-spew v1.1.1 // indirect
18 | github.com/fatih/color v1.18.0 // indirect
19 | github.com/fsnotify/fsnotify v1.8.0 // indirect
20 | github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
21 | github.com/inconshreveable/mousetrap v1.1.0 // indirect
22 | github.com/mattn/go-colorable v0.1.14 // indirect
23 | github.com/mattn/go-isatty v0.0.20 // indirect
24 | github.com/pelletier/go-toml/v2 v2.2.3 // indirect
25 | github.com/pkg/errors v0.9.1 // indirect
26 | github.com/pmezard/go-difflib v1.0.0 // indirect
27 | github.com/sagikazarmark/locafero v0.9.0 // indirect
28 | github.com/sourcegraph/conc v0.3.0 // indirect
29 | github.com/spf13/cast v1.7.1 // indirect
30 | github.com/spf13/pflag v1.0.6 // indirect
31 | github.com/subosito/gotenv v1.6.0 // indirect
32 | go.uber.org/multierr v1.11.0 // indirect
33 | golang.org/x/sys v0.31.0 // indirect
34 | golang.org/x/text v0.23.0 // indirect
35 | )
36 |
--------------------------------------------------------------------------------
/cmd/converge.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "github.com/apex/log"
5 | "github.com/spf13/cobra"
6 | "github.com/z0mbix/rolecule/pkg/config"
7 | )
8 |
9 | func init() {
10 | rootCmd.AddCommand(convergeCmd)
11 | }
12 |
13 | var convergeCmd = &cobra.Command{
14 | Use: "converge",
15 | Aliases: []string{"co"},
16 | Short: "Run your configuration management tool to converge the container(s)",
17 | Run: func(cmd *cobra.Command, args []string) {
18 | cfg, err := config.Get()
19 | if err != nil {
20 | log.Fatal(err.Error())
21 | }
22 |
23 | err = converge(cfg)
24 | if err != nil {
25 | log.Fatal(err.Error())
26 | }
27 | },
28 | }
29 |
30 | func converge(cfg *config.Config) error {
31 | for _, instance := range cfg.Instances {
32 | if !instance.Engine.Exists(instance.Name) {
33 | err := create(cfg)
34 | if err != nil {
35 | log.Error(err.Error())
36 | continue
37 | }
38 | }
39 |
40 | if len(instance.Provisioner.GetDependencies().GalaxyRoles) > 0 {
41 | log.Infof("preparing container %s", instance.Name)
42 | if err := instance.Prepare(); err != nil {
43 | log.Error(err.Error())
44 | }
45 | }
46 |
47 | log.Infof("converging container %s with %s", instance.Name, instance.Provisioner)
48 | if err := instance.Converge(); err != nil {
49 | log.Error(err.Error())
50 | }
51 | }
52 |
53 | return nil
54 | }
55 |
--------------------------------------------------------------------------------
/pkg/verifier/goss.go:
--------------------------------------------------------------------------------
1 | package verifier
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/apex/log"
7 | )
8 |
9 | type GossVerifier struct {
10 | Name string
11 | Command string
12 | Args []string
13 | ExtraArgs []string
14 | TestFile string
15 | }
16 |
17 | func (v GossVerifier) String() string {
18 | return v.Name
19 | }
20 |
21 | func (v GossVerifier) WithTestFile(file string) Verifier {
22 | v.TestFile = file
23 | return v
24 | }
25 |
26 | func (v GossVerifier) GetCommand() (map[string]string, string, []string) {
27 | gossfilePath := fmt.Sprintf("tests/%s", v.TestFile)
28 | args := []string{"--gossfile", gossfilePath, "validate"}
29 | args = append(args, v.ExtraArgs...)
30 | return nil, v.Command, args
31 | }
32 |
33 | func (v GossVerifier) GetTestFile() string {
34 | return v.TestFile
35 | }
36 |
37 | var defaultGossConfig = GossVerifier{
38 | Name: "goss",
39 | Command: "goss",
40 | TestFile: "goss.yaml",
41 | }
42 |
43 | func getGossConfig(config Config) GossVerifier {
44 | gossConfig := defaultGossConfig
45 | if config.TestFile != "" {
46 | log.Debugf("using gossfile from config file: %v", config.TestFile)
47 | gossConfig.TestFile = config.TestFile
48 | }
49 | if len(config.ExtraArgs) > 0 {
50 | log.Debugf("using goss extra args from config file: %v", config.ExtraArgs)
51 | gossConfig.ExtraArgs = config.ExtraArgs
52 | }
53 |
54 | return gossConfig
55 | }
56 |
--------------------------------------------------------------------------------
/pkg/command/command.go:
--------------------------------------------------------------------------------
1 | package command
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "os/exec"
7 | "strings"
8 |
9 | "github.com/apex/log"
10 | )
11 |
12 | func convertEnvVarMapToSlice(envVars map[string]string) []string {
13 | var envVarSlice []string
14 | for k, v := range envVars {
15 | envVarSlice = append(envVarSlice, fmt.Sprintf("%s=%s", k, v))
16 | }
17 |
18 | return envVarSlice
19 | }
20 |
21 | func Execute(name string, args ...string) (int, string, error) {
22 | return ExecuteWithEnvVars(nil, name, args...)
23 | }
24 |
25 | func ExecuteWithEnvVars(env map[string]string, name string, args ...string) (int, string, error) {
26 | cmd := exec.Command(name, args...)
27 | envVars := convertEnvVarMapToSlice(env)
28 | log.Debugf("executing command: %s with env vars: %+v", cmd, envVars)
29 | cmd.Env = envVars
30 | out, err := cmd.CombinedOutput()
31 | exitCode := cmd.ProcessState.ExitCode()
32 | if err != nil {
33 | return exitCode, string(out), fmt.Errorf("command failed: %s", err)
34 | }
35 | output := strings.TrimSuffix(string(out), "\n")
36 | return exitCode, output, nil
37 | }
38 |
39 | func Interactive(name string, args ...string) (int, error) {
40 | cmd := exec.Command(name, args...)
41 | log.Debugf("executing interactive command: %s", cmd)
42 | cmd.Stdout = os.Stdout
43 | cmd.Stdin = os.Stdin
44 | cmd.Stderr = os.Stderr
45 | err := cmd.Run()
46 | exitCode := cmd.ProcessState.ExitCode()
47 | if err != nil {
48 | return exitCode, fmt.Errorf("command failed: %s", err)
49 | }
50 | return exitCode, nil
51 | }
52 |
--------------------------------------------------------------------------------
/pkg/verifier/testinfra_test.go:
--------------------------------------------------------------------------------
1 | package verifier
2 |
3 | import (
4 | "reflect"
5 | "testing"
6 | )
7 |
8 | func TestTestInfraVerifier_String(t *testing.T) {
9 | tests := []struct {
10 | name string
11 | v TestInfraVerifier
12 | want string
13 | }{
14 | {
15 | name: "testinfra",
16 | v: defaultTestInfraConfig,
17 | want: "testinfra",
18 | },
19 | }
20 | for _, tt := range tests {
21 | t.Run(tt.name, func(t *testing.T) {
22 | if got := tt.v.String(); got != tt.want {
23 | t.Errorf("TestInfraVerifier.String() = %v, want %v", got, tt.want)
24 | }
25 | })
26 | }
27 | }
28 |
29 | func TestTestInfraVerifier_GetCommand(t *testing.T) {
30 | tests := []struct {
31 | name string
32 | v TestInfraVerifier
33 | want map[string]string
34 | want1 string
35 | want2 []string
36 | }{
37 | {
38 | name: "testinfra",
39 | v: defaultTestInfraConfig,
40 | want: nil,
41 | want1: "py.test",
42 | want2: []string{
43 | "-vv",
44 | "--hosts",
45 | "podman://foobar",
46 | },
47 | },
48 | }
49 | for _, tt := range tests {
50 | t.Run(tt.name, func(t *testing.T) {
51 | got, got1, got2 := tt.v.GetCommand()
52 | if !reflect.DeepEqual(got, tt.want) {
53 | t.Errorf("TestInfraVerifier.GetCommand() got = %v, want %v", got, tt.want)
54 | }
55 | if got1 != tt.want1 {
56 | t.Errorf("TestInfraVerifier.GetCommand() got1 = %v, want %v", got1, tt.want1)
57 | }
58 | if !reflect.DeepEqual(got2, tt.want2) {
59 | t.Errorf("TestInfraVerifier.GetCommand() got2 = %v, want %v", got2, tt.want2)
60 | }
61 | })
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/testing/ansible/ubuntu-22.04-systemd.Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:22.04
2 |
3 | ENV container=docker
4 | ENV DEBIAN_FRONTEND=noninteractive
5 |
6 | RUN sed -i 's/# deb/deb/g' /etc/apt/sources.list
7 |
8 | # hadolint ignore=DL3008
9 | RUN apt-get update \
10 | && apt-get install -y --no-install-recommends ca-certificates software-properties-common systemd curl cron gpg-agent less sudo bash iproute2 net-tools python3-apt vim \
11 | && apt-add-repository -y ppa:ansible/ansible 1>/dev/null \
12 | && apt-get install -y --no-install-recommends ansible ansible-lint \
13 | && apt-get clean \
14 | && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
15 |
16 | RUN dpkg-reconfigure ca-certificates
17 |
18 | WORKDIR /lib/systemd/system/sysinit.target.wants/
19 | # hadolint ignore=SC2010,SC2086
20 | RUN ls | grep -v systemd-tmpfiles-setup | xargs rm -f $1
21 |
22 | RUN rm -f /lib/systemd/system/multi-user.target.wants/* \
23 | /etc/systemd/system/*.wants/* \
24 | /lib/systemd/system/local-fs.target.wants/* \
25 | /lib/systemd/system/sockets.target.wants/*udev* \
26 | /lib/systemd/system/sockets.target.wants/*initctl* \
27 | /lib/systemd/system/basic.target.wants/* \
28 | /lib/systemd/system/anaconda.target.wants/* \
29 | /lib/systemd/system/plymouth* \
30 | /lib/systemd/system/systemd-update-utmp*
31 |
32 | # Install goss (https://github.com/goss-org/goss)
33 | RUN curl -sSL https://github.com/goss-org/goss/releases/latest/download/goss-linux-amd64 -o /usr/local/bin/goss && \
34 | chmod +rx /usr/local/bin/goss
35 |
36 | WORKDIR /
37 | RUN systemctl set-default multi-user.target
38 | ENV init=/lib/systemd/systemd
39 | VOLUME [ "/sys/fs/cgroup" ]
40 |
41 | ENTRYPOINT ["/lib/systemd/systemd"]
42 |
--------------------------------------------------------------------------------
/testing/ansible/ubuntu-24.04-systemd.Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:24.04
2 |
3 | ENV container=docker
4 | ENV DEBIAN_FRONTEND=noninteractive
5 |
6 | RUN sed -i 's/# deb/deb/g' /etc/apt/sources.list
7 |
8 | # hadolint ignore=DL3008
9 | RUN apt-get update \
10 | && apt-get install -y --no-install-recommends ca-certificates software-properties-common systemd curl cron gpg-agent less sudo bash iproute2 net-tools python3-apt vim \
11 | && apt-add-repository -y ppa:ansible/ansible 1>/dev/null \
12 | && apt-get install -y --no-install-recommends ansible ansible-lint \
13 | && apt-get clean \
14 | && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
15 |
16 | RUN dpkg-reconfigure ca-certificates
17 |
18 | WORKDIR /lib/systemd/system/sysinit.target.wants/
19 | # hadolint ignore=SC2010,SC2086
20 | RUN ls | grep -v systemd-tmpfiles-setup | xargs rm -f $1
21 |
22 | RUN rm -f /lib/systemd/system/multi-user.target.wants/* \
23 | /etc/systemd/system/*.wants/* \
24 | /lib/systemd/system/local-fs.target.wants/* \
25 | /lib/systemd/system/sockets.target.wants/*udev* \
26 | /lib/systemd/system/sockets.target.wants/*initctl* \
27 | /lib/systemd/system/basic.target.wants/* \
28 | /lib/systemd/system/anaconda.target.wants/* \
29 | /lib/systemd/system/plymouth* \
30 | /lib/systemd/system/systemd-update-utmp*
31 |
32 | # Install goss (https://github.com/goss-org/goss)
33 | RUN curl -sSL https://github.com/goss-org/goss/releases/latest/download/goss-linux-amd64 -o /usr/local/bin/goss && \
34 | chmod +rx /usr/local/bin/goss
35 |
36 | WORKDIR /
37 | RUN systemctl set-default multi-user.target
38 | ENV init=/lib/systemd/systemd
39 | VOLUME [ "/sys/fs/cgroup" ]
40 |
41 | ENTRYPOINT ["/lib/systemd/systemd"]
42 |
--------------------------------------------------------------------------------
/justfile:
--------------------------------------------------------------------------------
1 | set shell := ["bash", "-uc"]
2 |
3 | # Show available targets/recipes
4 | default:
5 | @just --choose
6 |
7 | # Clean up old files
8 | clean:
9 | rm -rf ./dist/*
10 | rm ./rolecule
11 |
12 | # Build the binary for the current os/arch
13 | build:
14 | go build -o bin/rolecule
15 |
16 | # Build the binary when go files change
17 | watch-build:
18 | fd .go | entr -c just build
19 |
20 | # Configure your host to use this repo
21 | setup:
22 | mise trust
23 | mise install
24 | mise ls -c
25 |
26 | # Show git tags
27 | tags:
28 | @git tag | sort -V
29 |
30 | # Run unit tests
31 | test:
32 | go test ./... -v -coverprofile=/dev/null
33 |
34 | # Build docker images with ansible support
35 | build-docker-ansible-images:
36 | docker build -t rockylinux-systemd:9.1 -f testing/ansible/rockylinux-9.1-systemd.Dockerfile .
37 | docker build -t ubuntu-systemd:22.04 -f testing/ansible/ubuntu-22.04-systemd.Dockerfile .
38 | docker build -t ubuntu-systemd:24.04 -f testing/ansible/ubuntu-24.04-systemd.Dockerfile .
39 |
40 | # Build podman images with ansible support
41 | build-podman-ansible-images:
42 | podman build -t rockylinux-systemd:9.1 -f testing/ansible/rockylinux-9.1-systemd.Dockerfile .
43 | podman build -t ubuntu-systemd:22.04 -f testing/ansible/ubuntu-22.04-systemd.Dockerfile .
44 | podman build -t ubuntu-systemd:24.04 -f testing/ansible/ubuntu-24.04-systemd.Dockerfile .
45 |
46 | # Build all images with ansible support
47 | build-ansible-images: build-docker-ansible-images build-podman-ansible-images
48 |
49 | # Build a local only, snapshot release
50 | snapshot:
51 | goreleaser --snapshot --skip-publish --rm-dist --debug
52 |
53 | # Create and publish a new release
54 | release:
55 | goreleaser --rm-dist
56 |
57 | # Show help menu
58 | help:
59 | @just --list --list-prefix ' ❯ '
60 |
--------------------------------------------------------------------------------
/pkg/verifier/goss_test.go:
--------------------------------------------------------------------------------
1 | package verifier
2 |
3 | import (
4 | "reflect"
5 | "testing"
6 | )
7 |
8 | func TestGossVerifier_String(t *testing.T) {
9 | tests := []struct {
10 | name string
11 | v GossVerifier
12 | want string
13 | }{
14 | {
15 | name: "goss",
16 | v: defaultGossConfig,
17 | want: "goss",
18 | },
19 | }
20 | for _, tt := range tests {
21 | t.Run(tt.name, func(t *testing.T) {
22 | if got := tt.v.String(); got != tt.want {
23 | t.Errorf("GossVerifier.String() = %v, want %v", got, tt.want)
24 | }
25 | })
26 | }
27 | }
28 |
29 | func TestGossVerifier_GetCommand(t *testing.T) {
30 | tests := []struct {
31 | name string
32 | v GossVerifier
33 | want map[string]string
34 | want1 string
35 | want2 []string
36 | }{
37 | {
38 | name: "goss",
39 | v: defaultGossConfig,
40 | want: nil,
41 | want1: "goss",
42 | want2: []string{
43 | "--gossfile",
44 | "tests/goss.yaml",
45 | "validate",
46 | },
47 | },
48 | {
49 | name: "goss-custom",
50 | v: GossVerifier{
51 | Name: "goss",
52 | Command: "goss",
53 | TestFile: "gossfile.yaml",
54 | ExtraArgs: []string{
55 | "--format",
56 | "json",
57 | },
58 | },
59 | want: nil,
60 | want1: "goss",
61 | want2: []string{
62 | "--gossfile",
63 | "tests/gossfile.yaml",
64 | "validate",
65 | "--format",
66 | "json",
67 | },
68 | },
69 | }
70 | for _, tt := range tests {
71 | t.Run(tt.name, func(t *testing.T) {
72 | got, got1, got2 := tt.v.GetCommand()
73 | if !reflect.DeepEqual(got, tt.want) {
74 | t.Errorf("GossVerifier.GetCommand() got = %v, want %v", got, tt.want)
75 | }
76 | if got1 != tt.want1 {
77 | t.Errorf("GossVerifier.GetCommand() got1 = %v, want %v", got1, tt.want1)
78 | }
79 | if !reflect.DeepEqual(got2, tt.want2) {
80 | t.Errorf("GossVerifier.GetCommand() got2 = %v, want %v", got2, tt.want2)
81 | }
82 | })
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/pkg/actions/actions.go:
--------------------------------------------------------------------------------
1 | package actions
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/z0mbix/rolecule/pkg/instance"
7 | )
8 |
9 | // Shell opens a shell in the specified container
10 | func Shell(instances instance.Instances, containerName string) error {
11 | targetInstance, err := findInstance(instances, containerName)
12 | if err != nil {
13 | return err
14 | }
15 |
16 | if !targetInstance.Exists() {
17 | return fmt.Errorf("container does not exist yet, you need to create it first")
18 | }
19 |
20 | return targetInstance.Shell()
21 | }
22 |
23 | // Exec executes a command in the specified container
24 | func Exec(instances instance.Instances, containerName string, cmd string, args []string) error {
25 | targetInstance, err := findInstance(instances, containerName)
26 | if err != nil {
27 | return err
28 | }
29 |
30 | if !targetInstance.Exists() {
31 | return fmt.Errorf("container does not exist yet, you need to create it first")
32 | }
33 |
34 | // Execute the command
35 | envVars := map[string]string{} // Empty map or add default environment variables
36 | return targetInstance.Engine.Exec(targetInstance.Name, envVars, cmd, args) // Assuming you added the interactive parameter
37 | }
38 |
39 | // findInstance finds an instance by name, or returns the first instance if no name is specified
40 | // or an error if multiple instances exist and no name is specified
41 | func findInstance(instances instance.Instances, containerName string) (instance.Instance, error) {
42 | if len(instances) == 0 {
43 | return instance.Instance{}, fmt.Errorf("no containers configured")
44 | }
45 |
46 | // If only one instance, use it
47 | if len(instances) == 1 {
48 | return instances[0], nil
49 | }
50 |
51 | // Multiple instances but no name specified
52 | if containerName == "" {
53 | var instanceNames []string
54 | for _, instance := range instances {
55 | instanceNames = append(instanceNames, instance.Name)
56 | }
57 | return instance.Instance{}, fmt.Errorf("more than one container, you need to specify which container with -n %v", instanceNames)
58 | }
59 |
60 | // Find the specified instance
61 | for _, instance := range instances {
62 | if instance.Name == containerName {
63 | return instance, nil
64 | }
65 | }
66 |
67 | return instance.Instance{}, fmt.Errorf("container %s not found", containerName)
68 | }
69 |
--------------------------------------------------------------------------------
/pkg/container/podman.go:
--------------------------------------------------------------------------------
1 | package container
2 |
3 | import (
4 | "fmt"
5 | "os"
6 |
7 | "github.com/apex/log"
8 | "github.com/z0mbix/rolecule/pkg/command"
9 | )
10 |
11 | type PodmanEngine struct {
12 | Name string
13 | Socket string
14 | }
15 |
16 | func (p *PodmanEngine) String() string {
17 | return p.Name
18 | }
19 |
20 | func (p *PodmanEngine) Run(image string, args []string) (string, error) {
21 | containerArgs := append(args, image)
22 | _, output, err := command.Execute(p.Name, containerArgs...)
23 | if err != nil {
24 | return output, err
25 | }
26 |
27 | return output, nil
28 | }
29 |
30 | func (p *PodmanEngine) Exec(containerName string, envVars map[string]string, cmd string, args []string) error {
31 | execArgs := []string{"exec"}
32 |
33 | if len(envVars) > 0 {
34 | for k, v := range envVars {
35 | execArgs = append(execArgs, "--env")
36 | execArgs = append(execArgs, fmt.Sprintf("%s=%s", k, os.ExpandEnv(v)))
37 | }
38 | }
39 |
40 | execArgs = append(execArgs, containerName)
41 | execArgs = append(execArgs, cmd)
42 | execArgs = append(execArgs, args...)
43 |
44 | _, err := command.Interactive(p.Name, execArgs...)
45 | return err
46 | }
47 |
48 | func (p *PodmanEngine) Shell(containerName string) error {
49 | shell := "bash"
50 | log.Debugf("opening %s shell in container", shell)
51 |
52 | args := []string{
53 | "exec",
54 | "--interactive",
55 | "--tty",
56 | containerName,
57 | shell,
58 | }
59 |
60 | _, err := command.Interactive(p.Name, args...)
61 | if err != nil {
62 | return err
63 | }
64 |
65 | return nil
66 | }
67 |
68 | func (p *PodmanEngine) Remove(name string) error {
69 | log.Debug("removing container")
70 |
71 | args := []string{
72 | "rm",
73 | "--force",
74 | name,
75 | }
76 | exitCode, _, err := command.Execute(p.Name, args...)
77 | if err != nil || exitCode != 0 {
78 | return err
79 | }
80 |
81 | return nil
82 | }
83 |
84 | func (p *PodmanEngine) Exists(name string) bool {
85 | log.Debug("checking if container already exists")
86 |
87 | args := []string{
88 | "container",
89 | "inspect",
90 | "--format",
91 | "{{.Name}}",
92 | name,
93 | }
94 |
95 | exitCode, output, err := command.Execute(p.Name, args...)
96 | if err != nil || exitCode != 0 {
97 | return false
98 | }
99 |
100 | return output == name
101 | }
102 |
103 | func (p *PodmanEngine) List(name string) (string, error) {
104 | args := []string{
105 | "ps",
106 | "--filter",
107 | fmt.Sprintf("name=%s", name),
108 | }
109 |
110 | exitCode, output, err := command.Execute(p.Name, args...)
111 | if err != nil || exitCode != 0 {
112 | return "", err
113 | }
114 |
115 | return output, nil
116 | }
117 |
--------------------------------------------------------------------------------
/pkg/container/docker.go:
--------------------------------------------------------------------------------
1 | package container
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "strings"
7 |
8 | "github.com/apex/log"
9 | "github.com/z0mbix/rolecule/pkg/command"
10 | )
11 |
12 | type DockerEngine struct {
13 | Name string
14 | Socket string
15 | }
16 |
17 | func (p *DockerEngine) String() string {
18 | return p.Name
19 | }
20 |
21 | func (p *DockerEngine) Run(image string, args []string) (string, error) {
22 | containerArgs := append(args, image)
23 | _, output, err := command.Execute(p.Name, containerArgs...)
24 | if err != nil {
25 | return output, err
26 | }
27 |
28 | return output, nil
29 | }
30 |
31 | func (p *DockerEngine) Exec(containerName string, envVars map[string]string, cmd string, args []string) error {
32 | execArgs := []string{"exec"}
33 |
34 | for k, v := range envVars {
35 | // Expand environment variables within the value if they exist using os.ExpandEnv
36 | execArgs = append(execArgs, "--env")
37 | execArgs = append(execArgs, fmt.Sprintf("%s=%s", k, os.ExpandEnv(v)))
38 | }
39 |
40 | execArgs = append(execArgs, containerName)
41 | execArgs = append(execArgs, cmd)
42 | execArgs = append(execArgs, args...)
43 |
44 | _, err := command.Interactive(p.Name, execArgs...)
45 | return err
46 | }
47 |
48 | func (p *DockerEngine) Shell(containerName string) error {
49 | shell := "bash"
50 | log.Debugf("opening %s shell in container", shell)
51 |
52 | args := []string{
53 | "exec",
54 | "--interactive",
55 | "--tty",
56 | containerName,
57 | shell,
58 | }
59 |
60 | _, err := command.Interactive(p.Name, args...)
61 | if err != nil {
62 | return err
63 | }
64 |
65 | return nil
66 | }
67 |
68 | func (p *DockerEngine) Remove(name string) error {
69 | log.Debug("removing container")
70 |
71 | args := []string{
72 | "rm",
73 | "--force",
74 | name,
75 | }
76 |
77 | exitCode, _, err := command.Execute(p.Name, args...)
78 | if err != nil || exitCode != 0 {
79 | return err
80 | }
81 |
82 | return nil
83 | }
84 |
85 | func (p *DockerEngine) Exists(name string) bool {
86 | log.Debug("checking if container already exists")
87 |
88 | args := []string{
89 | "container",
90 | "inspect",
91 | "--format",
92 | "{{.Name}}",
93 | name,
94 | }
95 |
96 | exitCode, output, err := command.Execute(p.Name, args...)
97 | if err != nil || exitCode != 0 {
98 | return false
99 | }
100 |
101 | // docker returns the container name with a forward slash prefix :(
102 | trimmedOutput := strings.TrimPrefix(output, "/")
103 | return trimmedOutput == name
104 | }
105 |
106 | func (p *DockerEngine) List(name string) (string, error) {
107 | args := []string{
108 | "ps",
109 | "--filter",
110 | fmt.Sprintf("name=%s", name),
111 | }
112 |
113 | exitCode, output, err := command.Execute(p.Name, args...)
114 | if err != nil || exitCode != 0 {
115 | return "", err
116 | }
117 |
118 | return output, nil
119 | }
120 |
--------------------------------------------------------------------------------
/pkg/instance/instance.go:
--------------------------------------------------------------------------------
1 | package instance
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "strings"
7 |
8 | "github.com/apex/log"
9 | "github.com/z0mbix/rolecule/pkg/container"
10 | "github.com/z0mbix/rolecule/pkg/provisioner"
11 | "github.com/z0mbix/rolecule/pkg/verifier"
12 | )
13 |
14 | type Instances []Instance
15 |
16 | type Config struct {
17 | Name string `mapstructure:"name"`
18 | Image string `mapstructure:"image"`
19 | Volumes []string `mapstructure:"volumes"`
20 | Arch string `mapstructure:"arch"`
21 | Args []string `mapstructure:"args"`
22 | Playbook string `mapstructure:"playbook"`
23 | TestFile string `mapstructure:"testfile"`
24 | SkipTags []string `mapstructure:"skip_tags"`
25 | Tags []string `mapstructure:"tags"`
26 | }
27 |
28 | type Instance struct {
29 | Name string
30 | Image string
31 | Arch string
32 | Args []string
33 | Playbook string
34 | TestFile string
35 | SkipTags []string
36 | Tags []string
37 | WorkDir string
38 | RoleName string
39 | RoleDir string
40 | RoleMounts map[string]string
41 | Volumes []string
42 | container.Engine
43 | Provisioner provisioner.Provisioner
44 | Verifier verifier.Verifier
45 | }
46 |
47 | func (i *Instance) Create() (string, error) {
48 | rolesPath := []string{"/etc/ansible/roles", i.RoleName}
49 | workDir := strings.Join(rolesPath, "/")
50 | instanceArgs := []string{
51 | "run",
52 | "--privileged",
53 | "--rm",
54 | "--detach",
55 | "--tmpfs", "/tmp",
56 | "--tmpfs", "/run",
57 | "--tmpfs", "/run/lock",
58 | "--tmpfs", "/var/lib/docker",
59 | "--cgroupns", "host",
60 | "--workdir", workDir,
61 | "--volume", "/sys/fs/cgroup:/sys/fs/cgroup:rw",
62 | "--volume", fmt.Sprintf("%s:%s", i.WorkDir, workDir),
63 | }
64 |
65 | for src, dst := range i.RoleMounts {
66 | instanceArgs = append(instanceArgs, "--volume", fmt.Sprintf("%s:%s", src, dst))
67 | }
68 |
69 | for _, volume := range i.Volumes {
70 | volume = strings.TrimSpace(volume)
71 | parts := strings.SplitN(volume, ":", 2)
72 |
73 | if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
74 | return "", fmt.Errorf("invalid volume format, expected 'hostPath:containerPath', got: %s", volume)
75 | }
76 |
77 | _, err := os.Stat(parts[0])
78 | if err != nil {
79 | if os.IsNotExist(err) {
80 | return "", fmt.Errorf("host path does not exist: %s", parts[0])
81 | }
82 | return "", fmt.Errorf("error accessing path: %s, error: %w", parts[0], err)
83 | }
84 |
85 | log.Debugf("mounting volume: %s -> %s", parts[0], parts[1])
86 | instanceArgs = append(instanceArgs, "--volume", fmt.Sprintf("%s:%s", parts[0], parts[1]))
87 | }
88 |
89 | if i.Arch != "" {
90 | instanceArgs = append(instanceArgs, "--platform", fmt.Sprintf("linux/%s", i.Arch))
91 | }
92 |
93 | instanceArgs = append(instanceArgs, "--name", i.Name)
94 |
95 | args := append(instanceArgs, i.Args...)
96 |
97 | log.Debugf("%+v", args)
98 | output, err := i.Run(i.Image, args)
99 | if err != nil {
100 | return output, err
101 | }
102 | return output, nil
103 | }
104 |
105 | func (i *Instance) Prepare() error {
106 | env, cmd, args := i.Provisioner.GetInstallDependenciesCommand()
107 | return i.Exec(i.Name, env, cmd, args)
108 | }
109 |
110 | func (i *Instance) Converge() error {
111 | env, cmd, args := i.Provisioner.GetCommand()
112 | return i.Exec(i.Name, env, cmd, args)
113 | }
114 |
115 | func (i *Instance) Verify() error {
116 | env, cmd, args := i.Verifier.GetCommand()
117 | return i.Exec(i.Name, env, cmd, args)
118 | }
119 |
120 | func (i *Instance) Shell() error {
121 | return i.Engine.Shell(i.Name)
122 | }
123 |
124 | func (i *Instance) Exists() bool {
125 | return i.Engine.Exists(i.Name)
126 | }
127 |
128 | func (i *Instance) Destroy() error {
129 | return i.Remove(i.Name)
130 | }
131 |
--------------------------------------------------------------------------------
/pkg/actions/actions_test.go:
--------------------------------------------------------------------------------
1 | package actions
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/stretchr/testify/assert"
7 | "github.com/z0mbix/rolecule/pkg/instance"
8 | )
9 |
10 | // Mock implementation of Engine for testing
11 | type mockEngine struct{}
12 |
13 | func (m *mockEngine) Run(image string, args []string) (string, error) { return "", nil }
14 | func (m *mockEngine) Exec(containerName string, envVars map[string]string, cmd string, args []string) error {
15 | return nil
16 | }
17 | func (m *mockEngine) Shell(containerName string) error { return nil }
18 | func (m *mockEngine) Remove(name string) error { return nil }
19 | func (m *mockEngine) Exists(name string) bool { return true }
20 | func (m *mockEngine) List(name string) (string, error) { return "", nil }
21 | func (m *mockEngine) String() string { return "mock" }
22 |
23 | func TestFindInstance(t *testing.T) {
24 | // Setup mock engine
25 | mockEng := &mockEngine{}
26 |
27 | // Test cases
28 | tests := []struct {
29 | name string
30 | instances instance.Instances
31 | containerName string
32 | expectedError bool
33 | expectedErrMsg string
34 | expectedName string
35 | }{
36 | {
37 | name: "no instances",
38 | instances: instance.Instances{},
39 | containerName: "",
40 | expectedError: true,
41 | expectedErrMsg: "no containers configured",
42 | },
43 | {
44 | name: "single instance, no name specified",
45 | instances: instance.Instances{
46 | {Name: "rolecule-test-ubuntu", Engine: mockEng},
47 | },
48 | containerName: "",
49 | expectedError: false,
50 | expectedName: "rolecule-test-ubuntu",
51 | },
52 | {
53 | name: "single instance, name matches",
54 | instances: instance.Instances{
55 | {Name: "rolecule-test-ubuntu", Engine: mockEng},
56 | },
57 | containerName: "rolecule-test-ubuntu",
58 | expectedError: false,
59 | expectedName: "rolecule-test-ubuntu",
60 | },
61 | {
62 | name: "multiple instances, no name specified",
63 | instances: instance.Instances{
64 | {Name: "rolecule-test-ubuntu", Engine: mockEng},
65 | {Name: "rolecule-test-centos", Engine: mockEng},
66 | },
67 | containerName: "",
68 | expectedError: true,
69 | expectedErrMsg: "more than one container",
70 | },
71 | {
72 | name: "multiple instances, name matches first",
73 | instances: instance.Instances{
74 | {Name: "rolecule-test-ubuntu", Engine: mockEng},
75 | {Name: "rolecule-test-centos", Engine: mockEng},
76 | },
77 | containerName: "rolecule-test-ubuntu",
78 | expectedError: false,
79 | expectedName: "rolecule-test-ubuntu",
80 | },
81 | {
82 | name: "multiple instances, name matches second",
83 | instances: instance.Instances{
84 | {Name: "rolecule-test-ubuntu", Engine: mockEng},
85 | {Name: "rolecule-test-centos", Engine: mockEng},
86 | },
87 | containerName: "rolecule-test-centos",
88 | expectedError: false,
89 | expectedName: "rolecule-test-centos",
90 | },
91 | {
92 | name: "multiple instances, name doesn't match any",
93 | instances: instance.Instances{
94 | {Name: "rolecule-test-ubuntu", Engine: mockEng},
95 | {Name: "rolecule-test-centos", Engine: mockEng},
96 | },
97 | containerName: "non-existent",
98 | expectedError: true,
99 | expectedErrMsg: "container non-existent not found",
100 | },
101 | }
102 |
103 | for _, tt := range tests {
104 | t.Run(tt.name, func(t *testing.T) {
105 | instance, err := findInstance(tt.instances, tt.containerName)
106 |
107 | if tt.expectedError {
108 | assert.Error(t, err)
109 | if tt.expectedErrMsg != "" {
110 | assert.Contains(t, err.Error(), tt.expectedErrMsg)
111 | }
112 | // Don't access instance if an error was expected
113 | return
114 | }
115 |
116 | // Only check instance properties if no error was expected
117 | assert.NoError(t, err)
118 | assert.Equal(t, tt.expectedName, instance.Name)
119 | })
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/pkg/provisioner/ansible.go:
--------------------------------------------------------------------------------
1 | package provisioner
2 |
3 | import (
4 | "strings"
5 |
6 | "github.com/apex/log"
7 | "golang.org/x/exp/maps"
8 | )
9 |
10 | type Dependencies struct {
11 | Collections []string
12 | LocalRoles []string
13 | GalaxyRoles []string
14 | }
15 |
16 | type AnsibleLocalProvisioner struct {
17 | Name string
18 | Command string
19 | Args []string
20 | ExtraArgs []string
21 | SkipTags []string
22 | Tags []string
23 | EnvVars map[string]string
24 | Playbook string
25 | Dependencies Dependencies
26 | }
27 |
28 | var ansibleRoleDir = "/etc/ansible/roles"
29 |
30 | var defaultAnsibleConfig = AnsibleLocalProvisioner{
31 | Name: "ansible",
32 | Command: "ansible-playbook",
33 | Args: []string{
34 | "--connection",
35 | "local",
36 | "--inventory",
37 | "localhost,",
38 | },
39 | EnvVars: map[string]string{
40 | "ANSIBLE_ROLES_PATH": ansibleRoleDir,
41 | "ANSIBLE_NOCOWS": "True",
42 | },
43 | Playbook: "playbook.yml",
44 | }
45 |
46 | func getAnsibleConfig(config Config) AnsibleLocalProvisioner {
47 | ansibleConfig := defaultAnsibleConfig
48 | if config.Command != "" {
49 | log.Debugf("using ansible command from config file: %v", config.Command)
50 | ansibleConfig.Command = config.Command
51 | }
52 |
53 | if len(config.Args) > 0 {
54 | log.Debugf("using ansible args from config file: %v", config.Args)
55 | ansibleConfig.Args = config.Args
56 | }
57 |
58 | if len(config.ExtraArgs) > 0 {
59 | log.Debugf("using ansible extra args from config file: %v", config.ExtraArgs)
60 | ansibleConfig.Args = append(ansibleConfig.Args, config.ExtraArgs...)
61 | }
62 |
63 | if len(config.EnvVars) > 0 {
64 | // Work around viper lowercasing map keys: https://github.com/spf13/viper/issues/373
65 | uppercaseEnv := make(map[string]string)
66 | for k, v := range config.EnvVars {
67 | uppercaseEnv[strings.ToUpper(k)] = v
68 | }
69 | log.Debugf("using extra ansible env from config file: %v", uppercaseEnv)
70 | maps.Copy(ansibleConfig.EnvVars, uppercaseEnv)
71 | }
72 |
73 | if config.Playbook != "" {
74 | log.Debugf("using ansible playbook from config file: %v", config.Playbook)
75 | ansibleConfig.Playbook = config.Playbook
76 | }
77 |
78 | return ansibleConfig
79 | }
80 |
81 | func (a AnsibleLocalProvisioner) WithExtraArgs(args []string) Provisioner {
82 | a.ExtraArgs = append(a.ExtraArgs, args...)
83 | return a
84 | }
85 |
86 | func (a AnsibleLocalProvisioner) WithSkipTags(tags []string) Provisioner {
87 | a.SkipTags = tags
88 | return a
89 | }
90 |
91 | func (a AnsibleLocalProvisioner) WithTags(tags []string) Provisioner {
92 | a.Tags = tags
93 | return a
94 | }
95 |
96 | func (a AnsibleLocalProvisioner) WithPlaybook(playbook string) Provisioner {
97 | a.Playbook = playbook
98 | return a
99 | }
100 |
101 | func (a AnsibleLocalProvisioner) WithLocalDependencies(dependencies []string) Provisioner {
102 | a.Dependencies.LocalRoles = dependencies
103 | return a
104 | }
105 |
106 | func (a AnsibleLocalProvisioner) WithGalaxyDependencies(dependencies []string) Provisioner {
107 | a.Dependencies.GalaxyRoles = dependencies
108 | return a
109 | }
110 |
111 | func (a AnsibleLocalProvisioner) GetDependencies() Dependencies {
112 | return a.Dependencies
113 | }
114 |
115 | func (a AnsibleLocalProvisioner) GetInstallDependenciesCommand() (map[string]string, string, []string) {
116 | log.Debugf("installing galaxy role(s):")
117 | args := []string{"install", "--roles-path", ansibleRoleDir}
118 | args = append(args, a.Dependencies.GalaxyRoles...)
119 |
120 | return a.EnvVars, "ansible-galaxy", args
121 | }
122 |
123 | func (a AnsibleLocalProvisioner) GetCommand() (map[string]string, string, []string) {
124 | testPlaybook := []string{testDirectory, a.Playbook}
125 | playbookPath := strings.Join(testPlaybook, "/")
126 | args := a.Args
127 |
128 | for _, tag := range a.Tags {
129 | args = append(args, "--tags")
130 | args = append(args, tag)
131 | }
132 |
133 | for _, tag := range a.SkipTags {
134 | args = append(args, "--skip-tags")
135 | args = append(args, tag)
136 | }
137 |
138 | args = append(args, playbookPath)
139 | return a.EnvVars, a.Command, args
140 | }
141 |
142 | func (a AnsibleLocalProvisioner) String() string {
143 | return a.Name
144 | }
145 |
--------------------------------------------------------------------------------
/pkg/config/config_test.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "path/filepath"
5 | "strings"
6 | "testing"
7 |
8 | "github.com/apex/log"
9 | "github.com/apex/log/handlers/memory"
10 | "github.com/spf13/afero"
11 | "github.com/stretchr/testify/require"
12 | "github.com/tj/assert"
13 | )
14 |
15 | func Test_generateContainerName(t *testing.T) {
16 | type args struct {
17 | name string
18 | roleName string
19 | }
20 | tests := []struct {
21 | name string
22 | args args
23 | want string
24 | }{
25 | {
26 | name: "ubuntu-22.04",
27 | args: args{
28 | name: "ubuntu-22.04",
29 | roleName: "foobar",
30 | },
31 | want: "rolecule-foobar-ubuntu-22.04",
32 | },
33 | {
34 | name: "arch",
35 | args: args{
36 | name: "arch",
37 | roleName: "i_use_arch_btw",
38 | },
39 | want: "rolecule-i-use-arch-btw-arch",
40 | },
41 | }
42 | for _, tt := range tests {
43 | t.Run(tt.name, func(t *testing.T) {
44 | if got := generateContainerName(tt.args.name, tt.args.roleName); got != tt.want {
45 | t.Errorf("generateContainerName() = %v, want %v", got, tt.want)
46 | }
47 | })
48 | }
49 | }
50 |
51 | func TestCreate(t *testing.T) {
52 | // Create memory handler for log testing
53 | handler := memory.New()
54 | log.SetHandler(handler)
55 |
56 | tests := []struct {
57 | name string
58 | engine string
59 | wantEngineSection bool
60 | setupFs func(afero.Fs) error
61 | wantErr bool
62 | wantErrMsg string
63 | }{
64 | {
65 | name: "with docker engine",
66 | engine: "docker",
67 | wantEngineSection: false,
68 | setupFs: func(fs afero.Fs) error { return nil },
69 | wantErr: false,
70 | },
71 | {
72 | name: "with podman engine",
73 | engine: "podman",
74 | wantEngineSection: true,
75 | setupFs: func(fs afero.Fs) error { return nil },
76 | wantErr: false,
77 | },
78 | {
79 | name: "with existing file",
80 | engine: "docker",
81 | wantEngineSection: false,
82 | setupFs: func(fs afero.Fs) error {
83 | if err := fs.MkdirAll(testsDir, 0755); err != nil {
84 | return err
85 | }
86 | return afero.WriteFile(fs, filepath.Join(testsDir, "rolecule.yml"), []byte("existing content"), 0644)
87 | },
88 | wantErr: true,
89 | wantErrMsg: filepath.Join(testsDir, "rolecule.yml") + " file already exists",
90 | },
91 | }
92 |
93 | for _, tt := range tests {
94 | t.Run(tt.name, func(t *testing.T) {
95 | // Reset log entries
96 | handler.Entries = nil
97 |
98 | // Save original filesystem and restore after test
99 | originalFs := appFs
100 | defer func() { appFs = originalFs }()
101 |
102 | // Create a new in-memory filesystem for each test
103 | mockFs := afero.NewMemMapFs()
104 | appFs = mockFs
105 |
106 | // Setup the filesystem if needed
107 | err := tt.setupFs(mockFs)
108 | require.NoError(t, err)
109 |
110 | // Call the Create function
111 | err = Create(tt.engine)
112 |
113 | if tt.wantErr {
114 | assert.Error(t, err)
115 | if tt.wantErrMsg != "" {
116 | assert.Contains(t, err.Error(), tt.wantErrMsg)
117 | }
118 |
119 | // If testing existing file case, verify file wasn't changed
120 | if tt.name == "with existing file" {
121 | content, err := afero.ReadFile(mockFs, filepath.Join(testsDir, "rolecule.yml"))
122 | require.NoError(t, err)
123 | assert.Equal(t, "existing content", string(content))
124 | }
125 | return
126 | }
127 |
128 | assert.NoError(t, err)
129 |
130 | // Check if the file was created
131 | configPath := filepath.Join(testsDir, "rolecule.yml")
132 | exists, err := afero.Exists(mockFs, configPath)
133 | require.NoError(t, err)
134 | assert.True(t, exists)
135 |
136 | // Read the file content
137 | content, err := afero.ReadFile(mockFs, configPath)
138 | require.NoError(t, err)
139 |
140 | // Check if the engine section is present or not
141 | expectedSection := "engine:\n name: " + tt.engine
142 | if tt.wantEngineSection {
143 | assert.Contains(t, string(content), expectedSection)
144 | } else {
145 | assert.NotContains(t, string(content), expectedSection)
146 | }
147 |
148 | // Check the file starts with "provisioner:" when engine is docker
149 | if !tt.wantEngineSection {
150 | assert.True(t, len(content) > 11)
151 | assert.Equal(t, "provisioner:", string(content)[:12])
152 | }
153 |
154 | // Verify other required sections are present
155 | assert.Contains(t, string(content), "provisioner:\n name: ansible")
156 | assert.Contains(t, string(content), "verifier:\n name: goss")
157 | assert.Contains(t, string(content), "instances:\n - name: ubuntu-24.04\n image: ubuntu-systemd:24.04")
158 |
159 | // Check log output
160 | found := false
161 | for _, entry := range handler.Entries {
162 | if entry.Level == log.InfoLevel &&
163 | strings.Contains(entry.Message, "created") &&
164 | strings.Contains(entry.Message, configPath) {
165 | found = true
166 | break
167 | }
168 | }
169 | assert.True(t, found, "Expected log message about file creation not found")
170 | })
171 | }
172 | }
173 |
--------------------------------------------------------------------------------
/pkg/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "bytes"
5 | "errors"
6 | "fmt"
7 | "html/template"
8 | "os"
9 | "path/filepath"
10 | "strings"
11 |
12 | "github.com/z0mbix/rolecule/pkg/filesystem"
13 |
14 | "github.com/apex/log"
15 | "github.com/spf13/afero"
16 | "github.com/spf13/viper"
17 | "github.com/z0mbix/rolecule/pkg/container"
18 | "github.com/z0mbix/rolecule/pkg/instance"
19 | "github.com/z0mbix/rolecule/pkg/provisioner"
20 | "github.com/z0mbix/rolecule/pkg/verifier"
21 | )
22 |
23 | var (
24 | AppName = "rolecule"
25 | defaultEngine = "docker"
26 | testsDir = "tests"
27 | appFs = afero.NewOsFs()
28 | )
29 |
30 | type configFile struct {
31 | Engine container.EngineConfig `mapstructure:"engine"`
32 | Provisioner provisioner.Config `mapstructure:"provisioner"`
33 | Verifier verifier.Config `mapstructure:"verifier"`
34 | Instances []instance.Config `mapstructure:"instances"`
35 | }
36 |
37 | type Config struct {
38 | RoleName string
39 | Instances instance.Instances
40 | Engine container.Engine
41 | }
42 |
43 | func Get() (*Config, error) {
44 | // config file is 'rolecule.yml|rolecule.yaml' in the current or 'tests' directory
45 | viper.SetEnvPrefix(strings.ToUpper(AppName))
46 | viper.SetConfigName(AppName)
47 | viper.SetConfigType("yaml")
48 | viper.AddConfigPath(".")
49 | viper.AddConfigPath(testsDir)
50 |
51 | if err := viper.ReadInConfig(); err != nil {
52 | var configFileNotFoundError viper.ConfigFileNotFoundError
53 | if errors.As(err, &configFileNotFoundError) {
54 | return nil, fmt.Errorf("config file not found")
55 | }
56 | }
57 |
58 | var configValues configFile
59 | err := viper.Unmarshal(&configValues)
60 | if err != nil {
61 | return nil, fmt.Errorf("unable to decode config file: %v", err)
62 | }
63 |
64 | log.Debugf("config file: %+v", configValues)
65 |
66 | if configValues.Engine.Name == "" {
67 | log.Debugf("engine not specified, using default engine: %s", defaultEngine)
68 | configValues.Engine.Name = defaultEngine
69 | }
70 | engine, err := container.NewEngine(configValues.Engine.Name)
71 | if err != nil {
72 | return nil, err
73 | }
74 |
75 | if !filesystem.CommandExists(configValues.Engine.Name) {
76 | return nil, fmt.Errorf("container engine '%s' not found in PATH", configValues.Engine.Name)
77 | }
78 |
79 | cwd, err := os.Getwd()
80 | if err != nil {
81 | return nil, err
82 | }
83 |
84 | // resolve any symlinks in the current working directory
85 | cwdNoSymlinks, err := filepath.EvalSymlinks(cwd)
86 | if err != nil {
87 | return nil, err
88 | }
89 |
90 | roleName := filepath.Base(cwd)
91 | roleDir := filepath.Dir(cwd)
92 | log.Debugf("role name: %s", roleName)
93 | log.Debugf("role dir: %s", roleDir)
94 |
95 | prov, err := provisioner.NewProvisioner(configValues.Provisioner)
96 | if err != nil {
97 | return nil, err
98 | }
99 |
100 | verif, err := verifier.NewVerifier(configValues.Verifier)
101 | if err != nil {
102 | return nil, err
103 | }
104 |
105 | // Check if the role has a meta/main.yml file to determine if it has dependencies
106 | roleMounts := make(map[string]string)
107 | if filesystem.FileExists("meta/main.yml") {
108 | roleMetadata, err := provisioner.GetRoleMetadata()
109 | if err != nil {
110 | return nil, err
111 | }
112 |
113 | for _, dep := range roleMetadata.LocalDependencies() {
114 | log.Debugf("found local role dependency: %s", dep)
115 | roleMounts[filepath.Join(roleDir, dep)] = filepath.Join("/etc/ansible/roles", dep)
116 | }
117 |
118 | for _, dep := range roleMetadata.GalaxyDependencies() {
119 | log.Debugf("found galaxy role dependency: %s", dep)
120 | }
121 |
122 | prov = prov.WithLocalDependencies(roleMetadata.LocalDependencies())
123 | prov = prov.WithGalaxyDependencies(roleMetadata.GalaxyDependencies())
124 | }
125 |
126 | var localRoleDependencies []string
127 | for _, v := range roleMounts {
128 | log.Debugf("adding local dependency: %s", v)
129 | localRoleDependencies = append(localRoleDependencies, v)
130 | }
131 |
132 | var instances instance.Instances
133 | for _, i := range configValues.Instances {
134 | iProvisioner := prov.WithTags(i.Tags).WithSkipTags(i.SkipTags)
135 |
136 | if i.Playbook != "" {
137 | iProvisioner = iProvisioner.WithPlaybook(i.Playbook)
138 | }
139 |
140 | iVerifier := verif
141 | if len(i.TestFile) > 0 {
142 | iVerifier = verif.WithTestFile(i.TestFile)
143 | }
144 |
145 | instanceConfig := instance.Instance{
146 | Name: generateContainerName(i.Name, roleName),
147 | Image: i.Image,
148 | Arch: i.Arch,
149 | Args: i.Args,
150 | Playbook: i.Playbook,
151 | WorkDir: cwdNoSymlinks,
152 | RoleName: roleName,
153 | RoleDir: roleDir,
154 | Engine: engine,
155 | Provisioner: iProvisioner,
156 | Verifier: iVerifier,
157 | RoleMounts: roleMounts,
158 | Volumes: i.Volumes,
159 | }
160 |
161 | instances = append(instances, instanceConfig)
162 | }
163 |
164 | cfg := &Config{
165 | RoleName: roleName,
166 | Engine: engine,
167 | Instances: instances,
168 | }
169 |
170 | return cfg, nil
171 | }
172 |
173 | func generateContainerName(name, roleName string) string {
174 | replacer := strings.NewReplacer("_", "-", " ", "-", ":", "-")
175 | return fmt.Sprintf("%s-%s-%s", AppName, replacer.Replace(roleName), replacer.Replace(name))
176 | }
177 |
178 | // Create creates a rolecule.yml file in the current directory
179 | func Create(engine string) error {
180 | log.Debugf("creating config with %s engine", engine)
181 |
182 | // Ensure the tests directory exists
183 | if err := appFs.MkdirAll(testsDir, 0755); err != nil {
184 | return fmt.Errorf("failed to create tests directory: %w", err)
185 | }
186 |
187 | // Define template for config file with conditional engine section
188 | // The template handles whitespace carefully to avoid extra blank lines
189 | configTemplate := `{{- if ne .Engine "docker" }}
190 | engine:
191 | name: {{ .Engine }}
192 |
193 | {{ end -}}
194 | provisioner:
195 | name: {{ .Provisioner }}
196 |
197 | verifier:
198 | name: {{ .Verifier }}
199 |
200 | instances:
201 | - name: ubuntu-24.04
202 | image: ubuntu-systemd:24.04
203 | `
204 |
205 | tmpl, err := template.New("config").Parse(configTemplate)
206 | if err != nil {
207 | return fmt.Errorf("failed to create template: %w", err)
208 | }
209 |
210 | data := struct {
211 | Engine string
212 | Provisioner string
213 | Verifier string
214 | }{
215 | Engine: engine,
216 | Provisioner: "ansible",
217 | Verifier: "goss",
218 | }
219 |
220 | var buf bytes.Buffer
221 | if err := tmpl.Execute(&buf, data); err != nil {
222 | return fmt.Errorf("failed to execute template: %w", err)
223 | }
224 |
225 | configPath := filepath.Join(testsDir, "rolecule.yml")
226 |
227 | // Check if file exists using Afero
228 | exists, err := afero.Exists(appFs, configPath)
229 | if err != nil {
230 | return fmt.Errorf("failed to check if file exists: %w", err)
231 | }
232 | if exists {
233 | return fmt.Errorf("%s file already exists", configPath)
234 | }
235 |
236 | // Write file using Afero
237 | if err := afero.WriteFile(appFs, configPath, buf.Bytes(), 0644); err != nil {
238 | return fmt.Errorf("failed to write config file: %w", err)
239 | }
240 |
241 | log.Infof("created %s", configPath)
242 | return nil
243 | }
244 |
--------------------------------------------------------------------------------
/pkg/provisioner/ansible_metadata.go:
--------------------------------------------------------------------------------
1 | package provisioner
2 |
3 | import (
4 | "fmt"
5 | "path/filepath"
6 | "strings"
7 |
8 | "github.com/apex/log"
9 | "github.com/z0mbix/rolecule/pkg/filesystem"
10 | "gopkg.in/yaml.v3"
11 | )
12 |
13 | // RoleMetadata represents the metadata of an Ansible role
14 | type RoleMetadata struct {
15 | Dependencies []interface{} `yaml:"dependencies"`
16 | resolvedDeps map[string]bool // To keep track of already resolved dependencies
17 | localPath string // Path to the role directory
18 | }
19 |
20 | // GetRoleMetadata reads the role metadata from meta/main.yml
21 | func GetRoleMetadata() (*RoleMetadata, error) {
22 | metadataFile := "meta/main.yml"
23 | data, err := filesystem.ReadFile(metadataFile)
24 | if err != nil {
25 | return nil, fmt.Errorf("failed to read metadata file: %w", err)
26 | }
27 |
28 | var metadata RoleMetadata
29 | if err := yaml.Unmarshal(data, &metadata); err != nil {
30 | return nil, fmt.Errorf("failed to unmarshal metadata: %w", err)
31 | }
32 |
33 | cwd, err := filesystem.GetCurrentDir()
34 | if err != nil {
35 | return nil, fmt.Errorf("failed to get current working directory: %w", err)
36 | }
37 |
38 | metadata.localPath = filepath.Dir(cwd)
39 | metadata.resolvedDeps = make(map[string]bool)
40 |
41 | return &metadata, nil
42 | }
43 |
44 | // AllLocalDependencies returns a complete list of all local dependencies (including nested ones)
45 | // and a map of role mount paths for use in container setup
46 | func (rm *RoleMetadata) AllLocalDependencies() ([]string, map[string]string, error) {
47 | allDeps := []string{}
48 | roleMounts := make(map[string]string)
49 |
50 | // Get direct and nested local dependencies
51 | localDeps := rm.LocalDependencies()
52 |
53 | // Generate mount paths for all dependencies
54 | for _, dep := range localDeps {
55 | srcPath := filepath.Join(rm.localPath, dep)
56 | dstPath := filepath.Join("/etc/ansible/roles", dep)
57 | roleMounts[srcPath] = dstPath
58 | allDeps = append(allDeps, dep)
59 |
60 | log.Debugf("adding mount for dependency %s: %s -> %s", dep, srcPath, dstPath)
61 | }
62 |
63 | return allDeps, roleMounts, nil
64 | }
65 |
66 | // LocalDependencies returns the list of local dependencies (both direct and nested)
67 | func (rm *RoleMetadata) LocalDependencies() []string {
68 | var localDeps []string
69 | depSet := make(map[string]bool) // Use a map to avoid duplicates
70 |
71 | // First, collect direct dependencies
72 | for _, dep := range rm.parseDependencies() {
73 | // Check if it's a local role (not a galaxy role)
74 | if !strings.Contains(dep, ".") && !strings.Contains(dep, "/") {
75 | if !depSet[dep] {
76 | depSet[dep] = true
77 | localDeps = append(localDeps, dep)
78 |
79 | // Now recursively resolve dependencies of this dependency
80 | log.Debugf("resolving dependencies for role: %s", dep)
81 | nestedDeps, err := rm.resolveNestedDependencies(dep)
82 | if err != nil {
83 | log.Warnf("failed to resolve dependencies for %s: %v", dep, err)
84 | continue
85 | }
86 |
87 | // Add nested dependencies
88 | for _, nestedDep := range nestedDeps {
89 | if !depSet[nestedDep] {
90 | depSet[nestedDep] = true
91 | localDeps = append(localDeps, nestedDep)
92 | log.Debugf("added nested dependency: %s", nestedDep)
93 | }
94 | }
95 | }
96 | }
97 | }
98 |
99 | log.Debugf("all local dependencies: %v", localDeps)
100 | return localDeps
101 | }
102 |
103 | // GalaxyDependencies returns the list of galaxy dependencies (both direct and nested)
104 | func (rm *RoleMetadata) GalaxyDependencies() []string {
105 | var galaxyDeps []string
106 | galaxyDepSet := make(map[string]bool)
107 |
108 | // Process direct dependencies
109 | for _, dep := range rm.parseDependencies() {
110 | // Check if it's a galaxy role (contains a dot)
111 | if strings.Contains(dep, ".") {
112 | if !galaxyDepSet[dep] {
113 | galaxyDepSet[dep] = true
114 | galaxyDeps = append(galaxyDeps, dep)
115 | }
116 | } else {
117 | // For local roles, we need to check their dependencies too
118 | nestedGalaxyDeps, err := rm.resolveNestedGalaxyDependencies(dep)
119 | if err != nil {
120 | log.Warnf("failed to resolve galaxy dependencies for %s: %v", dep, err)
121 | continue
122 | }
123 |
124 | // Add nested galaxy dependencies
125 | for _, nestedDep := range nestedGalaxyDeps {
126 | if !galaxyDepSet[nestedDep] {
127 | galaxyDepSet[nestedDep] = true
128 | galaxyDeps = append(galaxyDeps, nestedDep)
129 | log.Debugf("added nested galaxy dependency: %s", nestedDep)
130 | }
131 | }
132 | }
133 | }
134 |
135 | log.Debugf("all galaxy dependencies: %v", galaxyDeps)
136 | return galaxyDeps
137 | }
138 |
139 | // resolveNestedDependencies reads the dependencies of a dependency and returns all nested local dependencies
140 | func (rm *RoleMetadata) resolveNestedDependencies(roleName string) ([]string, error) {
141 | var nestedDeps []string
142 | depSet := make(map[string]bool) // Track dependencies to avoid duplicates
143 |
144 | // Construct path to the dependency's metadata file
145 | depMetaPath := filepath.Join(rm.localPath, roleName, "meta", "main.yml")
146 |
147 | // Check if metadata file exists
148 | if !filesystem.FileExists(depMetaPath) {
149 | log.Debugf("no metadata file found for role %s at %s", roleName, depMetaPath)
150 | return nestedDeps, nil // Return empty slice, not an error
151 | }
152 |
153 | // Read and parse the dependency's metadata
154 | data, err := filesystem.ReadFile(depMetaPath)
155 | if err != nil {
156 | return nil, fmt.Errorf("failed to read metadata for %s: %w", roleName, err)
157 | }
158 |
159 | var depMetadata RoleMetadata
160 | if err := yaml.Unmarshal(data, &depMetadata); err != nil {
161 | return nil, fmt.Errorf("failed to unmarshal metadata for %s: %w", roleName, err)
162 | }
163 |
164 | // Set the local path for the dependency
165 | depMetadata.localPath = rm.localPath
166 |
167 | // Get dependencies of this dependency
168 | for _, dep := range depMetadata.parseDependencies() {
169 | // Only process local dependencies
170 | if !strings.Contains(dep, ".") && !strings.Contains(dep, "/") {
171 | if !depSet[dep] {
172 | depSet[dep] = true
173 | nestedDeps = append(nestedDeps, dep)
174 | log.Debugf("found nested dependency: %s from role: %s", dep, roleName)
175 |
176 | // Recursively get dependencies of this dependency
177 | subDeps, err := rm.resolveNestedDependencies(dep)
178 | if err != nil {
179 | log.Warnf("failed to resolve sub-dependencies for %s: %v", dep, err)
180 | continue
181 | }
182 |
183 | // Add sub-dependencies
184 | for _, subDep := range subDeps {
185 | if !depSet[subDep] {
186 | depSet[subDep] = true
187 | nestedDeps = append(nestedDeps, subDep)
188 | log.Debugf("added sub-dependency: %s from role: %s", subDep, dep)
189 | }
190 | }
191 | }
192 | }
193 | }
194 |
195 | return nestedDeps, nil
196 | }
197 |
198 | // resolveNestedGalaxyDependencies reads the dependencies of a dependency and returns all nested galaxy dependencies
199 | func (rm *RoleMetadata) resolveNestedGalaxyDependencies(roleName string) ([]string, error) {
200 | var galaxyDeps []string
201 | galaxyDepSet := make(map[string]bool) // Track dependencies to avoid duplicates
202 |
203 | // Construct path to the dependency's metadata file
204 | depMetaPath := filepath.Join(rm.localPath, roleName, "meta", "main.yml")
205 |
206 | // Check if metadata file exists
207 | if !filesystem.FileExists(depMetaPath) {
208 | log.Debugf("no metadata file found for role %s at %s", roleName, depMetaPath)
209 | return galaxyDeps, nil // Return empty slice, not an error
210 | }
211 |
212 | // Read and parse the dependency's metadata
213 | data, err := filesystem.ReadFile(depMetaPath)
214 | if err != nil {
215 | return nil, fmt.Errorf("failed to read metadata for %s: %w", roleName, err)
216 | }
217 |
218 | var depMetadata RoleMetadata
219 | if err := yaml.Unmarshal(data, &depMetadata); err != nil {
220 | return nil, fmt.Errorf("failed to unmarshal metadata for %s: %w", roleName, err)
221 | }
222 |
223 | // Set the local path for the dependency
224 | depMetadata.localPath = rm.localPath
225 |
226 | // Get dependencies of this dependency
227 | for _, dep := range depMetadata.parseDependencies() {
228 | // Process galaxy dependencies
229 | if strings.Contains(dep, ".") || strings.Contains(dep, "/") {
230 | if !galaxyDepSet[dep] {
231 | galaxyDepSet[dep] = true
232 | galaxyDeps = append(galaxyDeps, dep)
233 | log.Debugf("found nested galaxy dependency: %s from role: %s", dep, roleName)
234 | }
235 | } else {
236 | // For local roles, check their galaxy dependencies
237 | nestedGalaxyDeps, err := rm.resolveNestedGalaxyDependencies(dep)
238 | if err != nil {
239 | log.Warnf("failed to resolve nested galaxy dependencies for %s: %v", dep, err)
240 | continue
241 | }
242 |
243 | // Add nested galaxy dependencies
244 | for _, nestedDep := range nestedGalaxyDeps {
245 | if !galaxyDepSet[nestedDep] {
246 | galaxyDepSet[nestedDep] = true
247 | galaxyDeps = append(galaxyDeps, nestedDep)
248 | log.Debugf("added nested galaxy dependency: %s from role: %s", nestedDep, dep)
249 | }
250 | }
251 | }
252 | }
253 |
254 | return galaxyDeps, nil
255 | }
256 |
257 | // parseDependencies parses the dependencies field and returns a list of role names
258 | func (rm *RoleMetadata) parseDependencies() []string {
259 | var dependencies []string
260 |
261 | for _, dep := range rm.Dependencies {
262 | switch v := dep.(type) {
263 | case string:
264 | dependencies = append(dependencies, v)
265 | case map[string]interface{}:
266 | if name, ok := v["name"].(string); ok {
267 | dependencies = append(dependencies, name)
268 | } else if role, ok := v["role"].(string); ok {
269 | dependencies = append(dependencies, role)
270 | }
271 | }
272 | }
273 |
274 | return dependencies
275 | }
276 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/apex/log v1.9.0 h1:FHtw/xuaM8AgmvDDTI9fiwoAL25Sq2cxojnZICUU8l0=
2 | github.com/apex/log v1.9.0/go.mod h1:m82fZlWIuiWzWP04XCTXmnX0xRkYYbCdYn8jbJeLBEA=
3 | github.com/apex/logs v1.0.0/go.mod h1:XzxuLZ5myVHDy9SAmYpamKKRNApGj54PfYLcFrXqDwo=
4 | github.com/aphistic/golf v0.0.0-20180712155816-02c07f170c5a/go.mod h1:3NqKYiepwy8kCu4PNA+aP7WUV72eXWJeP9/r3/K9aLE=
5 | github.com/aphistic/sweet v0.2.0/go.mod h1:fWDlIh/isSE9n6EPsRmC0det+whmX6dJid3stzu0Xys=
6 | github.com/aws/aws-sdk-go v1.20.6/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
7 | github.com/aybabtme/rgbterm v0.0.0-20170906152045-cc83f3b3ce59/go.mod h1:q/89r3U2H7sSsE2t6Kca0lfwTK8JdoNGS/yzM/4iH5I=
8 | github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
9 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
10 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
11 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
12 | github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
13 | github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
14 | github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
15 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
16 | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
17 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
18 | github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
19 | github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
20 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
21 | github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
22 | github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
23 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
24 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
25 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
26 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
27 | github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
28 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
29 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
30 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
31 | github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
32 | github.com/jpillora/backoff v0.0.0-20180909062703-3050d21c67d7/go.mod h1:2iMrUgbbvHEiQClaW2NsSzMyGHqN+rDFqY705q49KG0=
33 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
34 | github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
35 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
36 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
37 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
38 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
39 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
40 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
41 | github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
42 | github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
43 | github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
44 | github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
45 | github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
46 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
47 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
48 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
49 | github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
50 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
51 | github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
52 | github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
53 | github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
54 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
55 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
56 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
57 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
58 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
59 | github.com/rogpeppe/fastuuid v1.1.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
60 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
61 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
62 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
63 | github.com/sagikazarmark/locafero v0.9.0 h1:GbgQGNtTrEmddYDSAH9QLRyfAHY12md+8YFTqyMTC9k=
64 | github.com/sagikazarmark/locafero v0.9.0/go.mod h1:UBUyz37V+EdMS3hDF3QWIiVr/2dPrx49OMO0Bn0hJqk=
65 | github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
66 | github.com/smartystreets/assertions v1.0.0/go.mod h1:kHHU4qYBaI3q23Pp3VPrmWhuIUrLW/7eUrw0BU5VaoM=
67 | github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9/go.mod h1:SnhjPscd9TpLiy1LpzGSKh3bXCfxxXuqd9xmQJy3slM=
68 | github.com/smartystreets/gunit v1.0.0/go.mod h1:qwPWnhz6pn0NnRBP++URONOVyNkPyr4SauJk4cUOwJs=
69 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
70 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
71 | github.com/spf13/afero v1.14.0 h1:9tH6MapGnn/j0eb0yIXiLjERO8RB6xIVZRDCX7PtqWA=
72 | github.com/spf13/afero v1.14.0/go.mod h1:acJQ8t0ohCGuMN3O+Pv0V0hgMxNYDlvdk+VTfyZmbYo=
73 | github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
74 | github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
75 | github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
76 | github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
77 | github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
78 | github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
79 | github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4=
80 | github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
81 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
82 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
83 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
84 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
85 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
86 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
87 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
88 | github.com/tj/assert v0.0.0-20171129193455-018094318fb0/go.mod h1:mZ9/Rh9oLWpLLDRpvE+3b7gP/C2YyLFYxNmcLnPTMe0=
89 | github.com/tj/assert v0.0.3 h1:Df/BlaZ20mq6kuai7f5z2TvPFiwC3xaWJSDQNiIS3Rk=
90 | github.com/tj/assert v0.0.3/go.mod h1:Ne6X72Q+TB1AteidzQncjw9PabbMp4PBMZ1k+vd1Pvk=
91 | github.com/tj/go-buffer v1.1.0/go.mod h1:iyiJpfFcR2B9sXu7KvjbT9fpM4mOelRSDTbntVj52Uc=
92 | github.com/tj/go-elastic v0.0.0-20171221160941-36157cbbebc2/go.mod h1:WjeM0Oo1eNAjXGDx2yma7uG2XoyRZTq1uv3M/o7imD0=
93 | github.com/tj/go-kinesis v0.0.0-20171128231115-08b17f58cb1b/go.mod h1:/yhzCV0xPfx6jb1bBgRFjl5lytqVqZXEaeqWP8lTEao=
94 | github.com/tj/go-spin v1.1.0/go.mod h1:Mg1mzmePZm4dva8Qz60H2lHwmJ2loum4VIrLgVnKwh4=
95 | go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
96 | go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
97 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
98 | golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
99 | golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
100 | golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
101 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
102 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
103 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
104 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
105 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
106 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
107 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
108 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
109 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
110 | golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
111 | golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
112 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
113 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
114 | golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
115 | golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
116 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
117 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
118 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
119 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
120 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
121 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
122 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
123 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
124 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
125 | gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
126 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
127 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
128 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Rolecule
2 |
3 | ## Description
4 |
5 | `rolecule` is a simple tool to help you test your ansible roles by creating systemd enabled containers with either docker or podman, then converging them with ansible. We're basically treating containers as mini VMs.
6 |
7 | Once converged, it will run a verifier to test it all. Currently, the only supported provisioner is [goss](https://github.com/goss-org/goss), but others may be added at some point in the future.
8 |
9 | This should speed up testing your roles if you're currently using local or remote virtual machines.
10 |
11 | ## Usage
12 |
13 | First, you need to create a simple `rolecule.yml` file in either the root of your role or in the `tests` directory, e.g.:
14 |
15 | ```yaml
16 | ---
17 | engine:
18 | name: podman
19 |
20 | provisioner:
21 | name: ansible
22 |
23 | verifier:
24 | name: goss
25 |
26 | instances:
27 | - name: rockylinux-9.1
28 | image: rockylinux-systemd:9.1
29 | - name: ubuntu-22.04
30 | image: ubuntu-systemd:22.04
31 |
32 | ```
33 |
34 | Then, from the root of your role (e.g. [sshd](testing/ansible/roles/sshd/tests/rolecule.yml)), run `rolecule test`, e.g.:
35 |
36 | ```text
37 | » rolecule test
38 | • creating container rolecule-sshd-rockylinux-9.1 with podman
39 | • creating container rolecule-sshd-ubuntu-22.04 with podman
40 | • converging container rolecule-sshd-rockylinux-9.1 with ansible
41 | Using /etc/ansible/ansible.cfg as config file
42 |
43 | PLAY [test] ********************************************************************
44 | ...
45 |
46 | PLAY RECAP *********************************************************************
47 | localhost : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
48 |
49 | • converging container rolecule-sshd-ubuntu-22.04 with ansible
50 | No config file found; using defaults
51 |
52 | PLAY [test] ********************************************************************
53 | ...
54 |
55 | PLAY RECAP *********************************************************************
56 | localhost : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
57 |
58 | • verifying container rolecule-sshd-rockylinux-9.1 with goss
59 | ............
60 |
61 | Total Duration: 0.016s
62 | Count: 12, Failed: 0, Skipped: 0
63 |
64 | • verifying container rolecule-sshd-ubuntu-22.04 with goss
65 | ............
66 |
67 | Total Duration: 0.015s
68 | Count: 12, Failed: 0, Skipped: 0
69 |
70 | • destroying container rolecule-sshd-rockylinux-9.1
71 | • destroying container rolecule-sshd-ubuntu-22.04
72 | • complete
73 | ```
74 |
75 | ## Help
76 |
77 | ```text
78 | » rolecule --help
79 | rolecule uses docker or podman to test your
80 | ansible roles in a systemd enabled container,
81 | then tests them with a verifier (goss).
82 |
83 | Usage:
84 | rolecule [command]
85 |
86 | Available Commands:
87 | completion Generate the autocompletion script for the specified shell
88 | converge Run your configuration management tool to converge the container(s)
89 | create Create a new container(s) to test the role in
90 | destroy Destroy everything
91 | exec Execute a command in a container
92 | help Help about any command
93 | init Initialise the project with a tests directory and a rolecule.yml file
94 | list List the running containers for this role/module/recipe
95 | shell Open a shell in a container
96 | test Create the container(s), converge them, and test them
97 | verify Verify your containers are configured how you expect
98 | version Show version
99 |
100 | Flags:
101 | -d, --debug enable debug output
102 | -h, --help help for rolecule
103 |
104 | Use "rolecule [command] --help" for more information about a command.
105 | ```
106 |
107 | ## Individual sub command examples
108 |
109 | Create the containers:
110 |
111 | ```text
112 | » rolecule create
113 | • creating container rolecule-sshd-rockylinux-9.1 with podman
114 | • creating container rolecule-sshd-ubuntu-22.04 with podman
115 | ```
116 |
117 | List all containers:
118 |
119 | ```text
120 | » rolecule list
121 | CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
122 | e9638f571210 localhost/rockylinux-systemd:9.1 /usr/sbin/init 21 minutes ago Up 21 minutes ago rolecule-sshd-rockylinux-9.1
123 | 0e07e4214fd5 localhost/ubuntu-systemd:22.04 21 minutes ago Up 21 minutes ago rolecule-sshd-ubuntu-22.04
124 | ```
125 |
126 | Open a shell:
127 |
128 | ```text
129 | » rolecule shell -n rolecule-sshd-ubuntu-22.04
130 | root@0e07e4214fd5:/src#
131 | ```
132 |
133 | Destroy the containers:
134 |
135 | ```text
136 | » rolecule destroy
137 | • destroying container rolecule-sshd-rockylinux-9.1
138 | • destroying container rolecule-sshd-ubuntu-22.04
139 | ```
140 |
141 | ## Provisioners
142 |
143 | ### Ansible
144 |
145 | The default for the ansible provisioner is the equivalent to setting the following in the `rolecule.yml` config file:
146 |
147 | ```yaml
148 | provisioner:
149 | name: ansible
150 | command: ansible-playbook
151 | playbook: playbook.yml
152 | args:
153 | - --connection
154 | - local
155 | - --inventory
156 | - localhost,
157 | - tests/playbook.yml
158 | extra_args: []
159 | env:
160 | ANSIBLE_ROLES_PATH: .
161 | ANSIBLE_NOCOWS: True
162 | ```
163 |
164 | If you want to add extra environment variables you can just add them to the `env` map, e.g.:
165 |
166 | ```yaml
167 | provisioner:
168 | name: ansible
169 | env:
170 | ANSIBLE_NOCOLOR: True
171 | ```
172 |
173 | If you want to run a completely different ansible command, you can override the command and all the args with the `command` and `args` keys respectively, but if you just want to add other args like `--diff` or `--verbose`, add them to the `extra_args` array, e.g.:
174 |
175 | ```yaml
176 | provisioner:
177 | name: ansible
178 | extra_args:
179 | - --diff
180 | - --verbose
181 | ```
182 |
183 | ## Role dependencies
184 |
185 | If you have role dependencies in your `meta/main.yml` file using local roles in the same location
186 | as the current role, they will be mounted at `/etc/ansible/roles` in the container so
187 | ansible can find them. Currently, only local roles and ansible galaxy roles are supported.
188 |
189 | ## Instances
190 |
191 | These are instances of each test scenario, allowing you to test different ansible tags with specific test files.
192 |
193 | A simple example for a single Ubuntu test would be:
194 |
195 | ```yaml
196 | instances:
197 | - name: ubuntu-22.04
198 | image: ubuntu-systemd:22.04
199 | ```
200 |
201 | Something more elaborate:
202 |
203 | ```yaml
204 | instances:
205 | - name: ubuntu-22.04
206 | image: ubuntu-systemd:22.04
207 | playbook: ubuntu/playbook.yml
208 | volumes:
209 | - /var/run/docker.sock:/var/run/docker.sock
210 | - name: ubuntu-22.04-build
211 | image: ubuntu-systemd:22.04
212 | arch: amd64
213 | playbook: ubuntu/playbook.yml
214 | testfile: goss-build.yaml
215 | tags:
216 | - build
217 | - name: rockylinux-9.1
218 | image: rockylinux-systemd:9.1
219 | - name: rockylinux-9.1-build
220 | image: rockylinux-systemd:9.1
221 | testfile: goss-build.yaml
222 | tags:
223 | - build
224 | skip_tags:
225 | - provision
226 | ```
227 |
228 | Where the above will test two different scenarios for each of the Ubuntu and Rocky Linux containers.
229 |
230 | If you do not specify the testfile in the instance config, it will use the one specified in the verifier config.
231 |
232 | If you do not specify the playbook in the instance config, it will use the one specified in the provisioner config.
233 |
234 | Testing multiple architectures is support, but untested as I don't currently have an easy way to test it, but should be as simple as something like:
235 |
236 | ```yaml
237 | instances:
238 | - name: ubuntu-22.04-amd64
239 | image: ubuntu-systemd:22.04
240 | arch: amd64
241 | - name: ubuntu-22.04-arm64
242 | image: ubuntu-systemd:22.04
243 | arch: arm64
244 | ```
245 |
246 | If you don't specify the arch, it will use the current host's architecture
247 |
248 | Please note that if you do want to test using a different architecture to the host your are running it on,
249 | you will need to have the relevant container image for that architecture.
250 |
251 | ## Verifiers
252 |
253 | ### Goss
254 |
255 | The default goss configuration when you only specify the name, is equivalent to this:
256 |
257 | ```yaml
258 | verifier:
259 | name: goss
260 | testfile: goss.yaml
261 | extra_args: []
262 | ```
263 |
264 | This will execute:
265 |
266 | ```text
267 | goss --gossfile tests/goss.yaml validate
268 | ```
269 |
270 | If you want to customise how goss validate is executed, you can change the gossfile and add extra arguments to the validate subcommand, e.g. with this in your `rolecule.yml`:
271 |
272 | ```yaml
273 | verifier:
274 | name: goss
275 | testfile: goss-build.yaml
276 | extra_args:
277 | - --format
278 | - tap
279 | ```
280 |
281 | It will execute:
282 |
283 | ```text
284 | goss --gossfile tests/goss-build.yaml validate --format tap
285 | ```
286 |
287 | ### FAQ
288 |
289 | **How do I get this working on macOS?**
290 |
291 | You'll need to make sure you create a rootful podman machine with your home directory mounted for volume mounts to work, e.g.:
292 |
293 | ```text
294 | » podman machine init --now --rootful -v $HOME:$HOME
295 | ```
296 |
297 | Docker Desktop should just work
298 |
299 | **How do I get this working on Windows?**
300 |
301 | You'll need to make sure you create a rootful podman machine, e.g.:
302 |
303 | ```text
304 | » podman machine init --now --rootful
305 | ```
306 |
307 | Docker Desktop should just work
308 |
309 | **How do I create a suitable container image for this?**
310 |
311 | You can use the `Dockerfile` files in the testing directory to build suitable images:
312 |
313 | ```text
314 | » podman build -t rockylinux-systemd:9.1 -f testing/ansible/rockylinux-9.1-systemd.Dockerfile .
315 | » podman build -t ubuntu-systemd:22.04 -f testing/ansible/ubuntu-22.04-systemd.Dockerfile .
316 | » podman build -t amazonlinux2-systemd:2 -f testing/ansible/amazonlinux2-systemd.Dockerfile .
317 | ```
318 |
319 | or
320 |
321 | ```text
322 | » docker build -t rockylinux-systemd:9.1 -f testing/ansible/rockylinux-9.1-systemd.Dockerfile .
323 | » docker build -t ubuntu-systemd:22.04 -f testing/ansible/ubuntu-22.04-systemd.Dockerfile .
324 | » docker build -t amazonlinux2-systemd:2 -f testing/ansible/amazonlinux2-systemd.Dockerfile .
325 | ```
326 |
327 | **How do I install collections?**
328 |
329 | For now, I've been building in my collections in to the container images in the default location so they
330 | are discovered automatically by ansible.
331 |
332 | ## TODO
333 |
334 | - ~~Test with podman on Mac~~
335 | - ~~Test docker on Linux~~
336 | - ~~Make provisioner output unbuffered~~
337 | - ~~Support installing role dependencies~~
338 | - Support installing ansible collections?
339 | - ~~Support scenarios, making it possible to test a role with different tags~~
340 | - ~~Support using custom provisioner command/args/env vars from rolecule.yml~~
341 | - ~~Support using custom verifier command/args/env vars from rolecule.yml~~
342 | - ~~Implement `rolecule init` to generate a rolecule.yml file (use current directory structure to determine configuration management provisioner)~~
343 | - ~~Implement `rolecule list` subcommand to list all running containers~~
344 | - ~~Write some tests :/~~
345 | - ~~Document what is required for a container image~~
346 | - ~~Test with docker on Linux~~
347 | - ~~Test with docker desktop on Mac~~
348 | - ~~Test with podman desktop on Windows~~
349 | - ~~Test with docker desktop on Windows~~
350 | - ~~Add goreleaser config to release to Github Releases~~
351 | - ~~Add Github actions workflow to build, test and release~~
352 |
--------------------------------------------------------------------------------
/pkg/provisioner/ansible_test.go:
--------------------------------------------------------------------------------
1 | package provisioner
2 |
3 | import (
4 | "reflect"
5 | "strings"
6 | "testing"
7 | )
8 |
9 | func TestAnsibleProvisioner_String(t *testing.T) {
10 | tests := []struct {
11 | name string
12 | a AnsibleLocalProvisioner
13 | want string
14 | }{
15 | {
16 | name: "Ansible",
17 | a: defaultAnsibleConfig,
18 | want: "ansible",
19 | },
20 | }
21 | for _, tt := range tests {
22 | t.Run(tt.name, func(t *testing.T) {
23 | if got := tt.a.String(); got != tt.want {
24 | t.Errorf("AnsibleProvisioner.String() = %v, want %v", got, tt.want)
25 | }
26 | })
27 | }
28 | }
29 |
30 | func TestAnsibleProvisioner_GetCommand(t *testing.T) {
31 | tests := []struct {
32 | name string
33 | a AnsibleLocalProvisioner
34 | want map[string]string
35 | want1 string
36 | want2 []string
37 | }{
38 | {
39 | name: "command",
40 | a: defaultAnsibleConfig,
41 | want: map[string]string{
42 | "ANSIBLE_ROLES_PATH": "/etc/ansible/roles",
43 | "ANSIBLE_NOCOWS": "True",
44 | },
45 | want1: "ansible-playbook",
46 | want2: []string{
47 | "--connection",
48 | "local",
49 | "--inventory",
50 | "localhost,",
51 | strings.Join([]string{"tests", "playbook.yml"}, "/"),
52 | },
53 | },
54 | }
55 | for _, tt := range tests {
56 | t.Run(tt.name, func(t *testing.T) {
57 | got, got1, got2 := tt.a.GetCommand()
58 | if !reflect.DeepEqual(got, tt.want) {
59 | t.Errorf("AnsibleProvisioner.GetCommand() got = %v, want %v", got, tt.want)
60 | }
61 | if got1 != tt.want1 {
62 | t.Errorf("AnsibleProvisioner.GetCommand() got1 = %v, want %v", got1, tt.want1)
63 | }
64 | if !reflect.DeepEqual(got2, tt.want2) {
65 | t.Errorf("AnsibleProvisioner.GetCommand() got2 = %v, want %v", got2, tt.want2)
66 | }
67 | })
68 | }
69 | }
70 |
71 | func TestAnsibleLocalProvisioner_WithExtraArgs(t *testing.T) {
72 | type fields struct {
73 | Name string
74 | }
75 | type args struct {
76 | args []string
77 | }
78 | tests := []struct {
79 | name string
80 | fields fields
81 | args args
82 | want Provisioner
83 | }{
84 | {
85 | name: "MultipleExtraArgs",
86 | fields: fields{
87 | Name: "ansible",
88 | },
89 | args: args{
90 | args: []string{
91 | "--diff",
92 | "--verbose",
93 | },
94 | },
95 | want: AnsibleLocalProvisioner{
96 | Name: "ansible",
97 | ExtraArgs: []string{"--diff", "--verbose"},
98 | },
99 | },
100 | }
101 | for _, tt := range tests {
102 | t.Run(tt.name, func(t *testing.T) {
103 | a := AnsibleLocalProvisioner{
104 | Name: tt.fields.Name,
105 | }
106 | if got := a.WithExtraArgs(tt.args.args); !reflect.DeepEqual(got, tt.want) {
107 | t.Errorf("WithExtraArgs() = %v, want %v", got, tt.want)
108 | }
109 | })
110 | }
111 | }
112 |
113 | func TestAnsibleLocalProvisioner_WithTags(t *testing.T) {
114 | type fields struct {
115 | Name string
116 | }
117 | type args struct {
118 | args []string
119 | }
120 | tests := []struct {
121 | name string
122 | fields fields
123 | args args
124 | want Provisioner
125 | }{
126 | {
127 | name: "MultipleTags",
128 | fields: fields{
129 | Name: "ansible",
130 | },
131 | args: args{
132 | args: []string{
133 | "build",
134 | "configure",
135 | },
136 | },
137 | want: AnsibleLocalProvisioner{
138 | Name: "ansible",
139 | Tags: []string{"build", "configure"},
140 | },
141 | },
142 | }
143 | for _, tt := range tests {
144 | t.Run(tt.name, func(t *testing.T) {
145 | a := AnsibleLocalProvisioner{
146 | Name: tt.fields.Name,
147 | }
148 | if got := a.WithTags(tt.args.args); !reflect.DeepEqual(got, tt.want) {
149 | t.Errorf("WithExtraArgs() = %v, want %v", got, tt.want)
150 | }
151 | })
152 | }
153 | }
154 |
155 | func TestAnsibleLocalProvisioner_WithSkipTags(t *testing.T) {
156 | type fields struct {
157 | Name string
158 | }
159 | type args struct {
160 | args []string
161 | }
162 | tests := []struct {
163 | name string
164 | fields fields
165 | args args
166 | want Provisioner
167 | }{
168 | {
169 | name: "SkipTags",
170 | fields: fields{
171 | Name: "ansible",
172 | },
173 | args: args{
174 | args: []string{
175 | "ignore",
176 | },
177 | },
178 | want: AnsibleLocalProvisioner{
179 | Name: "ansible",
180 | SkipTags: []string{"ignore"},
181 | },
182 | },
183 | }
184 | for _, tt := range tests {
185 | t.Run(tt.name, func(t *testing.T) {
186 | a := AnsibleLocalProvisioner{
187 | Name: tt.fields.Name,
188 | }
189 | if got := a.WithSkipTags(tt.args.args); !reflect.DeepEqual(got, tt.want) {
190 | t.Errorf("WithExtraArgs() = %v, want %v", got, tt.want)
191 | }
192 | })
193 | }
194 | }
195 |
196 | func TestAnsibleLocalProvisioner_WithPlaybook(t *testing.T) {
197 | type fields struct {
198 | Name string
199 | Command string
200 | Args []string
201 | ExtraArgs []string
202 | SkipTags []string
203 | Tags []string
204 | EnvVars map[string]string
205 | Playbook string
206 | Dependencies Dependencies
207 | }
208 | type args struct {
209 | playbook string
210 | }
211 | tests := []struct {
212 | name string
213 | fields fields
214 | args args
215 | want Provisioner
216 | }{
217 | {
218 | name: "Playbook",
219 | fields: fields{
220 | Name: "ansible",
221 | },
222 | args: args{
223 | playbook: "playbook.yaml",
224 | },
225 | want: AnsibleLocalProvisioner{
226 | Name: "ansible",
227 | Playbook: "playbook.yaml",
228 | },
229 | },
230 | }
231 | for _, tt := range tests {
232 | t.Run(tt.name, func(t *testing.T) {
233 | a := AnsibleLocalProvisioner{
234 | Name: tt.fields.Name,
235 | Playbook: tt.fields.Playbook,
236 | }
237 | if got := a.WithPlaybook(tt.args.playbook); !reflect.DeepEqual(got, tt.want) {
238 | t.Errorf("WithPlaybook() = %v, want %v", got, tt.want)
239 | }
240 | })
241 | }
242 | }
243 |
244 | func TestAnsibleLocalProvisioner_WithLocalDependencies(t *testing.T) {
245 | type fields struct {
246 | Name string
247 | Command string
248 | Args []string
249 | ExtraArgs []string
250 | SkipTags []string
251 | Tags []string
252 | EnvVars map[string]string
253 | Playbook string
254 | Dependencies Dependencies
255 | }
256 | type args struct {
257 | dependencies []string
258 | }
259 | tests := []struct {
260 | name string
261 | fields fields
262 | args args
263 | want Provisioner
264 | }{
265 | {
266 | name: "local",
267 | fields: fields{
268 | Name: "ansible",
269 | },
270 | args: args{
271 | dependencies: []string{
272 | "depone",
273 | "deptwo",
274 | },
275 | },
276 | want: AnsibleLocalProvisioner{
277 | Name: "ansible",
278 | Dependencies: Dependencies{
279 | LocalRoles: []string{
280 | "depone",
281 | "deptwo",
282 | },
283 | },
284 | },
285 | },
286 | }
287 | for _, tt := range tests {
288 | t.Run(tt.name, func(t *testing.T) {
289 | a := AnsibleLocalProvisioner{
290 | Name: tt.fields.Name,
291 | Dependencies: tt.fields.Dependencies,
292 | }
293 | if got := a.WithLocalDependencies(tt.args.dependencies); !reflect.DeepEqual(got, tt.want) {
294 | t.Errorf("WithLocalDependencies() = %v, want %v", got, tt.want)
295 | }
296 | })
297 | }
298 | }
299 |
300 | func TestAnsibleLocalProvisioner_WithGalaxyDependencies(t *testing.T) {
301 | type fields struct {
302 | Name string
303 | Dependencies Dependencies
304 | }
305 | type args struct {
306 | dependencies []string
307 | }
308 | tests := []struct {
309 | name string
310 | fields fields
311 | args args
312 | want Provisioner
313 | }{
314 | {
315 | name: "galaxy",
316 | fields: fields{
317 | Name: "ansible",
318 | },
319 | args: args{
320 | dependencies: []string{
321 | "z0mbix.depone",
322 | "z0mbix.deptwo",
323 | },
324 | },
325 | want: AnsibleLocalProvisioner{
326 | Name: "ansible",
327 | Dependencies: Dependencies{
328 | GalaxyRoles: []string{
329 | "z0mbix.depone",
330 | "z0mbix.deptwo",
331 | },
332 | },
333 | },
334 | },
335 | }
336 | for _, tt := range tests {
337 | t.Run(tt.name, func(t *testing.T) {
338 | a := AnsibleLocalProvisioner{
339 | Name: tt.fields.Name,
340 | Dependencies: tt.fields.Dependencies,
341 | }
342 | if got := a.WithGalaxyDependencies(tt.args.dependencies); !reflect.DeepEqual(got, tt.want) {
343 | t.Errorf("WithGalaxyDependencies() = %+v, want %+v", got, tt.want)
344 | }
345 | })
346 | }
347 | }
348 |
349 | func TestAnsibleLocalProvisioner_GetInstallDependenciesCommand(t *testing.T) {
350 | type fields struct {
351 | Name string
352 | Command string
353 | Args []string
354 | ExtraArgs []string
355 | SkipTags []string
356 | Tags []string
357 | EnvVars map[string]string
358 | Playbook string
359 | Dependencies Dependencies
360 | }
361 | tests := []struct {
362 | name string
363 | fields fields
364 | want map[string]string
365 | want1 string
366 | want2 []string
367 | }{
368 | {
369 | name: "basic",
370 | fields: fields{
371 | Name: "ansible",
372 | Command: "ansible-playbook",
373 | Dependencies: Dependencies{
374 | Collections: nil,
375 | LocalRoles: nil,
376 | GalaxyRoles: []string{
377 | "z0mbix.depone",
378 | "z0mbix.deptwo",
379 | },
380 | },
381 | },
382 | want: nil,
383 | //want: map[string]string{
384 | // "ANSIBLE_ROLES_PATH": "/etc/ansible/roles",
385 | // "ANSIBLE_NOCOWS": "True",
386 | //},
387 | want1: "ansible-galaxy",
388 | want2: []string{
389 | "install",
390 | "--roles-path",
391 | "/etc/ansible/roles",
392 | "z0mbix.depone",
393 | "z0mbix.deptwo",
394 | },
395 | },
396 | }
397 | for _, tt := range tests {
398 | t.Run(tt.name, func(t *testing.T) {
399 | a := AnsibleLocalProvisioner{
400 | Name: tt.fields.Name,
401 | Command: tt.fields.Command,
402 | Args: tt.fields.Args,
403 | ExtraArgs: tt.fields.ExtraArgs,
404 | SkipTags: tt.fields.SkipTags,
405 | Tags: tt.fields.Tags,
406 | EnvVars: tt.fields.EnvVars,
407 | Playbook: tt.fields.Playbook,
408 | Dependencies: tt.fields.Dependencies,
409 | }
410 | got, got1, got2 := a.GetInstallDependenciesCommand()
411 | if !reflect.DeepEqual(got, tt.want) {
412 | t.Errorf("GetInstallDependenciesCommand() got = %v, want %v", got, tt.want)
413 | }
414 | if got1 != tt.want1 {
415 | t.Errorf("GetInstallDependenciesCommand() got1 = %v, want %v", got1, tt.want1)
416 | }
417 | if !reflect.DeepEqual(got2, tt.want2) {
418 | t.Errorf("GetInstallDependenciesCommand() got2 = %v, want %v", got2, tt.want2)
419 | }
420 | })
421 | }
422 | }
423 |
424 | func TestAnsibleLocalProvisioner_GetCommand(t *testing.T) {
425 | type fields struct {
426 | Name string
427 | Command string
428 | Args []string
429 | ExtraArgs []string
430 | SkipTags []string
431 | Tags []string
432 | EnvVars map[string]string
433 | Playbook string
434 | Dependencies Dependencies
435 | }
436 | tests := []struct {
437 | name string
438 | fields fields
439 | want map[string]string
440 | want1 string
441 | want2 []string
442 | }{
443 | {
444 | name: "basic",
445 | fields: fields{
446 | Name: "ansible",
447 | Command: "ansible-playbook",
448 | EnvVars: map[string]string{
449 | "ANSIBLE_ROLES_PATH": "/etc/ansible/roles",
450 | "ANSIBLE_NOCOWS": "True",
451 | },
452 | Args: []string{
453 | "--connection",
454 | "local",
455 | "--inventory",
456 | "localhost,",
457 | },
458 | Playbook: "playbook.yml",
459 | },
460 | want: map[string]string{
461 | "ANSIBLE_ROLES_PATH": "/etc/ansible/roles",
462 | "ANSIBLE_NOCOWS": "True",
463 | },
464 | want1: "ansible-playbook",
465 | want2: []string{
466 | "--connection",
467 | "local",
468 | "--inventory",
469 | "localhost,",
470 | strings.Join([]string{"tests", "playbook.yml"}, "/"),
471 | },
472 | },
473 | }
474 | for _, tt := range tests {
475 | t.Run(tt.name, func(t *testing.T) {
476 | a := AnsibleLocalProvisioner{
477 | Name: tt.fields.Name,
478 | Command: tt.fields.Command,
479 | Args: tt.fields.Args,
480 | ExtraArgs: tt.fields.ExtraArgs,
481 | SkipTags: tt.fields.SkipTags,
482 | Tags: tt.fields.Tags,
483 | EnvVars: tt.fields.EnvVars,
484 | Playbook: tt.fields.Playbook,
485 | Dependencies: tt.fields.Dependencies,
486 | }
487 | got, got1, got2 := a.GetCommand()
488 | if !reflect.DeepEqual(got, tt.want) {
489 | t.Errorf("GetCommand() got = %v, want %v", got, tt.want)
490 | }
491 | if got1 != tt.want1 {
492 | t.Errorf("GetCommand() got1 = %v, want %v", got1, tt.want1)
493 | }
494 | if !reflect.DeepEqual(got2, tt.want2) {
495 | t.Errorf("GetCommand() got2 = %v, want %v", got2, tt.want2)
496 | }
497 | })
498 | }
499 | }
500 |
501 | func Test_getAnsibleConfig(t *testing.T) {
502 | type args struct {
503 | config Config
504 | }
505 | tests := []struct {
506 | name string
507 | args args
508 | want AnsibleLocalProvisioner
509 | }{
510 | {
511 | name: "foobar",
512 | args: args{
513 | config: Config{
514 | Name: "foo",
515 | },
516 | },
517 | want: AnsibleLocalProvisioner{
518 | Name: "ansible",
519 | Command: "ansible-playbook",
520 | Args: []string{
521 | "--connection",
522 | "local",
523 | "--inventory",
524 | "localhost,",
525 | },
526 | EnvVars: map[string]string{
527 | "ANSIBLE_ROLES_PATH": ansibleRoleDir,
528 | "ANSIBLE_NOCOWS": "True",
529 | },
530 | Playbook: "playbook.yml",
531 | },
532 | },
533 | }
534 | for _, tt := range tests {
535 | t.Run(tt.name, func(t *testing.T) {
536 | if got := getAnsibleConfig(tt.args.config); !reflect.DeepEqual(got, tt.want) {
537 | t.Errorf("getAnsibleConfig() = %v, want %v", got, tt.want)
538 | }
539 | })
540 | }
541 | }
542 |
543 | func TestAnsibleLocalProvisioner_String(t *testing.T) {
544 | type fields struct {
545 | Name string
546 | Command string
547 | Args []string
548 | ExtraArgs []string
549 | SkipTags []string
550 | Tags []string
551 | EnvVars map[string]string
552 | Playbook string
553 | Dependencies Dependencies
554 | }
555 | tests := []struct {
556 | name string
557 | fields fields
558 | want string
559 | }{
560 | {
561 | name: "ansible",
562 | fields: fields{
563 | Name: "ansible",
564 | },
565 | want: "ansible",
566 | },
567 | }
568 | for _, tt := range tests {
569 | t.Run(tt.name, func(t *testing.T) {
570 | a := AnsibleLocalProvisioner{
571 | Name: tt.fields.Name,
572 | }
573 | if got := a.String(); got != tt.want {
574 | t.Errorf("String() = %v, want %v", got, tt.want)
575 | }
576 | })
577 | }
578 | }
579 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------