Skip to content

Commit

Permalink
Add --no-hosts flag to eliminate use of /etc/hosts within containers
Browse files Browse the repository at this point in the history
Users want to turn off addition of /etc/hosts file while building
container images, this would allow them to customize the /etc/hosts
file within the image.

Fixes: #3808

Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>
  • Loading branch information
rhatdan committed Mar 8, 2022
1 parent a97a904 commit 43a7769
Show file tree
Hide file tree
Showing 12 changed files with 50 additions and 6 deletions.
3 changes: 3 additions & 0 deletions cmd/buildah/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type runInputOptions struct {
mounts []string
runtime string
runtimeFlag []string
noHosts bool
noPivot bool
terminal bool
volumes []string
Expand Down Expand Up @@ -66,6 +67,7 @@ func init() {
// Do not set a default runtime here, we'll do that later in the processing.
flags.StringVar(&opts.runtime, "runtime", util.Runtime(), "`path` to an alternate OCI runtime")
flags.StringSliceVar(&opts.runtimeFlag, "runtime-flag", []string{}, "add global flags for the container runtime")
flags.BoolVar(&opts.noHosts, "no-hosts", false, "do not override /etc/hosts file within the container")
flags.BoolVar(&opts.noPivot, "no-pivot", false, "do not use pivot root to jail process inside rootfs")
flags.BoolVarP(&opts.terminal, "terminal", "t", false, "allocate a pseudo-TTY in the container")
flags.StringArrayVarP(&opts.volumes, "volume", "v", []string{}, "bind mount a host location into the container while running the command")
Expand Down Expand Up @@ -127,6 +129,7 @@ func runCmd(c *cobra.Command, args []string, iopts runInputOptions) error {
Hostname: iopts.hostname,
Runtime: iopts.runtime,
Args: runtimeFlags,
NoHosts: iopts.noHosts,
NoPivot: noPivot,
User: c.Flag("user").Value.String(),
Isolation: isolation,
Expand Down
7 changes: 5 additions & 2 deletions define/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,14 @@ type CommonBuildOptions struct {
DNSServers []string
// DNSOptions is the list of DNS
DNSOptions []string
// MemorySwap limits the amount of memory and swap together.
MemorySwap int64
// LabelOpts is the a slice of fields of an SELinux context, given in "field:pair" format, or "disable".
// Recognized field names are "role", "type", and "level".
LabelOpts []string
// MemorySwap limits the amount of memory and swap together.
MemorySwap int64
// NoHosts tells the builder not create /etc/hosts content when running
// containers.
NoHosts bool
// OmitTimestamp forces epoch 0 as created timestamp to allow for
// deterministic, content-addressable builds.
OmitTimestamp bool
Expand Down
9 changes: 8 additions & 1 deletion docs/buildah-build.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ When a Git repository is set as the URL, the repository is cloned locally and th

Add a custom host-to-IP mapping (host:ip)

Add a line to /etc/hosts. The format is hostname:ip. The **--add-host** option can be set multiple times.
Add a line to /etc/hosts. The format is hostname:ip. The **--add-host** option can be set multiple times. Conflicts with the --no-hosts option.

**--all-platforms**

Expand Down Expand Up @@ -396,6 +396,13 @@ Valid _mode_ values are:

Do not use existing cached images for the container build. Build from the start with a new set of cached layers.

**--no-hosts**

Do not create _/etc/hosts_ for the container.

By default, Buildah manages _/etc/hosts_, adding the container's own IP address.
**--no-hosts** disables this, and the image's _/etc/hosts_ will be preserved unmodified. Conflicts with the --add-host option.

**--os**="OS"

Set the OS of the image to be built, and that of the base image to be pulled, if the build uses one, instead of using the current operating system of the host.
Expand Down
7 changes: 7 additions & 0 deletions docs/buildah-run.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,13 @@ consult the manpages of the selected container runtime.
Note: Do not pass the leading `--` to the flag. To pass the runc flag `--log-format json`
to buildah run, the option given would be `--runtime-flag log-format=json`.

**--no-hosts**

Do not create _/etc/hosts_ for the container.

By default, Buildah manages _/etc/hosts_, adding the container's own IP address.
**--no-hosts** disables this, and the image's _/etc/hosts_ will be preserved unmodified.

**--no-pivot**

Do not use pivot root to jail process inside rootfs. This should be used
Expand Down
2 changes: 2 additions & 0 deletions imagebuildah/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ type Executor struct {
labels []string
annotations []string
layers bool
noHosts bool
useCache bool
removeIntermediateCtrs bool
forceRmIntermediateCtrs bool
Expand Down Expand Up @@ -245,6 +246,7 @@ func newExecutor(logger *logrus.Logger, logPrefix string, store storage.Store, o
labels: append([]string{}, options.Labels...),
annotations: append([]string{}, options.Annotations...),
layers: options.Layers,
noHosts: options.CommonBuildOpts.NoHosts,
useCache: !options.NoCache,
removeIntermediateCtrs: options.RemoveIntermediateCtrs,
forceRmIntermediateCtrs: options.ForceRmIntermediateCtrs,
Expand Down
1 change: 1 addition & 0 deletions imagebuildah/stage_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@ func (s *StageExecutor) Run(run imagebuilder.Run, config docker.Config) error {
Hostname: config.Hostname,
Runtime: s.executor.runtime,
Args: s.executor.runtimeArgs,
NoHosts: s.executor.noHosts,
NoPivot: os.Getenv("BUILDAH_NOPIVOT") != "",
Mounts: append([]Mount{}, s.executor.transientMounts...),
Env: config.Env,
Expand Down
2 changes: 2 additions & 0 deletions pkg/cli/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ type BudResults struct {
Label []string
Logfile string
Manifest string
NoHosts bool
NoCache bool
Timestamp int64
Pull string
Expand Down Expand Up @@ -212,6 +213,7 @@ func GetBudFlags(flags *BudResults) pflag.FlagSet {
panic(fmt.Sprintf("error marking the rusage-logfile flag as hidden: %v", err))
}
fs.StringVar(&flags.Manifest, "manifest", "", "add the image to the specified manifest list. Creates manifest list if it does not exist")
fs.BoolVar(&flags.NoHosts, "no-hosts", false, "Do not create new containers /etc/hosts file, use the one from the current image.")
fs.BoolVar(&flags.NoCache, "no-cache", false, "Do not use existing cached images for the container build. Build from the start with a new set of cached layers.")
fs.String("os", runtime.GOOS, "set the OS to the provided value instead of the current operating system of the host")
fs.StringVar(&flags.Pull, "pull", "true", "pull the image from the registry if newer or not present in store, if false, only pull the image if not present, if always, pull the image even if the named image is present in store, if never, only use the image present in store if available")
Expand Down
6 changes: 6 additions & 0 deletions pkg/parse/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,13 @@ func CommonBuildOptionsFromFlagSet(flags *pflag.FlagSet, findFlagFunc func(name
}
}

noHosts, _ := flags.GetBool("no-hosts")

addHost, _ := flags.GetStringSlice("add-host")
if len(addHost) > 0 {
if noHosts {
return nil, errors.Errorf("--no-hosts and --add-host conflict, can not be used together")
}
for _, host := range addHost {
if err := validateExtraHost(host); err != nil {
return nil, errors.Wrapf(err, "invalid value for add-host")
Expand Down Expand Up @@ -159,6 +164,7 @@ func CommonBuildOptionsFromFlagSet(flags *pflag.FlagSet, findFlagFunc func(name
HTTPProxy: httpProxy,
Memory: memoryLimit,
MemorySwap: memorySwap,
NoHosts: noHosts,
ShmSize: findFlagFunc("shm-size").Value.String(),
Ulimit: ulimit,
Volumes: volumes,
Expand Down
2 changes: 2 additions & 0 deletions run.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ type RunOptions struct {
Runtime string
// Args adds global arguments for the runtime.
Args []string
// NoHosts use the images /etc/hosts file
NoHosts bool
// NoPivot adds the --no-pivot runtime flag.
NoPivot bool
// Mounts are additional mount points which we want to provide.
Expand Down
2 changes: 1 addition & 1 deletion run_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ func (b *Builder) Run(command []string, options RunOptions) error {
namespaceOptions := append(b.NamespaceOptions, options.NamespaceOptions...)
volumes := b.Volumes()

if !contains(volumes, "/etc/hosts") {
if !options.NoHosts && !contains(volumes, "/etc/hosts") {
hostFile, err := b.generateHosts(path, spec.Hostname, b.CommonBuildOpts.AddHost, rootIDPair)
if err != nil {
return err
Expand Down
9 changes: 9 additions & 0 deletions tests/bud.bats
Original file line number Diff line number Diff line change
Expand Up @@ -3171,6 +3171,15 @@ _EOF
run_buildah build --add-host=myhostname:$ip -t testbud \
--signature-policy ${TESTSDIR}/policy.json --file ${mytmpdir} .
expect_output --from="${lines[2]}" --substring "^$ip\s+myhostname"

run_buildah 125 build --no-cache --add-host=myhostname:$ip \
--no-hosts \
--signature-policy ${TESTSDIR}/policy.json --file ${mytmpdir} .
expect_output --substring "\-\-no-hosts and \-\-add-host conflict, can not be used together"

run_buildah 1 build --no-cache --no-hosts \
--signature-policy ${TESTSDIR}/policy.json --file ${mytmpdir} .
expect_output --substring 'error building at STEP "RUN grep "myhostname" /etc/hosts'
}

@test "bud with --cgroup-parent" {
Expand Down
6 changes: 4 additions & 2 deletions tests/run.bats
Original file line number Diff line number Diff line change
Expand Up @@ -590,8 +590,7 @@ function configure_and_check_user() {
run_buildah from --quiet --pull=false --signature-policy ${TESTSDIR}/policy.json debian
cid=$output
run_buildah 125 run --network=bogus $cid cat /etc/hosts
expect_output --substring "unable to find network with name or ID bogus: network not found"

expect_output --substring "unable to find network with name or ID bogus: network not found"
run_buildah run $cid cat /etc/hosts
expect_output --substring "127.0.0.1.*$cid"
expect_output --substring "::1.*$cid"
Expand All @@ -609,11 +608,14 @@ function configure_and_check_user() {
run_buildah from --quiet --pull=false --signature-policy ${TESTSDIR}/policy.json debian
cid=$output
run_buildah run --network=host $cid cat /etc/hosts
hostOutput=$output
expect_output --substring "# Generated by Buildah"
m=$(buildah mount $cid)
run cat $m/etc/hosts
[ "$status" -eq 0 ]
expect_output --substring ""
run_buildah run --network=host --no-hosts $cid cat /etc/hosts
[ "$output" != "$hostOutput" ]
run_buildah rm -a

run_buildah from --quiet --pull=false --signature-policy ${TESTSDIR}/policy.json debian
Expand Down

0 comments on commit 43a7769

Please sign in to comment.