<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[.debug - Medium]]></title>
        <description><![CDATA[Software development, security, and more. - Medium]]></description>
        <link>https://medium.com/dot-debug?source=rss----9a12780e40b3---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>.debug - Medium</title>
            <link>https://medium.com/dot-debug?source=rss----9a12780e40b3---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:19:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/dot-debug" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is that Golang thing, anyways?]]></title>
            <link>https://medium.com/dot-debug/what-is-that-golang-thing-anyways-e8063b017611?source=rss----9a12780e40b3---4</link>
            <guid isPermaLink="false">https://medium.com/p/e8063b017611</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Stephen Fox]]></dc:creator>
            <pubDate>Thu, 19 Oct 2017 03:01:47 GMT</pubDate>
            <atom:updated>2017-10-19T03:15:57.597Z</atom:updated>
            <content:encoded><![CDATA[<p>Searching for “just the right” language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oi7u14Jdjj8P-ZbEEUyVYw.png" /><figcaption><em>The Golang mascot, Gopher. Credit </em><a href="https://upload.wikimedia.org/wikipedia/commons/thumb/2/23/Golang.png/1200px-Golang.png"><em>wikimedia.org</em></a></figcaption></figure><p>Golang is a powerful, easy to learn programming language created by engineers at Google that has soared in popularity in recent years. It is so popular, that <a href="https://krebsonsecurity.com/2017/01/who-is-anna-senpai-the-mirai-worm-author/">botnet builders</a> are using it! Today, I am going to discuss the case for Go — and hopefully help you break through some of the language’s eccentricities.</p><h3>Goldilocks</h3><p>Several months ago, I set out to create a library that would interoperate with other programming languages without creating a maintenance nightmare. It would need to be easy to learn for new comers, be well supported in development tools such as IDEs and dependency management tools, and be supported on multiple platforms with minimal dependency overhead.</p><p>Along the way, I read about Go and the passion that many programmers had for it. Three features in particular caught my eye:</p><ul><li>A single project can be easily compiled to a single, static executable targeted for popular platforms such as Linux, macOS, and Windows</li><li>Like C# .NET and Java, Go relies on a runtime. However, a compiled executable does not require the runtime to be present. The executable is less than 10 megabytes on disk. The garbage collector also has a negligible impact on the application’s performance</li><li>Compartmentalizing code into libraries is easy, and is promoted by the compiler rejecting cyclic dependencies</li></ul><p>While these features did not entirely solve my “perfect” library problem, they made a very strong case for exploring the language’s capabilities.</p><h3>Initial eccentricities</h3><p>Like all programming languages, Go has a learning curve and its share of non-obvious nuances. During my reading, I encountered both love and hate for many of Go’s qualities. In this section, I will discuss several non-obvious qualities that are especially important for newcomers to understand.</p><h4>Projects are managed with ‘go get&#39; and the GOPATH</h4><p>After <a href="https://golang.org/dl/">installing the Go runtime</a>, you will need to create the GOPATH. This is the filesystem location where all of your Go projects <em>should</em> live. There is nothing stopping you from creating Go projects outside of the GOPATH. If you do this, you will quickly discover that many features of the ‘go’ command line tool will not work with your project.</p><p>You are expected to use the go command line tool to acquire existing Go projects. Under the hood, Go wraps around your source control management tool of choice. By default, Go assumes that the GOPATH is a directory named ‘go’, which lives in your home directory (~/go). You can change this by creating an environment variable of the same name, whose value is the desired location.</p><p>Existing Go projects are acquired using the go get &lt;project-url&gt; command. These projects are added to the GOPATH, in the structure of:</p><p>&lt;GOPATH&gt;/src/&lt;repository-host.com&gt;/&lt;your-identity&gt;/&lt;project-name&gt;</p><p>For example, running:</p><p>go get https://github.com/stephen-fox/power</p><p>… would result in the Git project being cloned to:</p><p>~/go/src/github.com/stephen-fox/power</p><p>Go expects you to follow this convention when you create a new project. What differs in project creation is that you must manually create the directory structure shown above — the go tool will not do that for you. As a result, you must know which source control tool and repository host you are using before you create a project. While this promotes the usage of source control tools, it unfortunately forces developers to bend their workflow to the tool.</p><h4>Dependencies are managed in packages</h4><p>A Go package is a self-contained codebase that exposes public functions to a caller. It is synonymous with a library. Members of a package are identified with the package keyword at the top of a .go source file. Public functions are exposed outside of the package by capitalizing the first letter of the function’s name.</p><p>For example, if you wanted to write a package that exposed a function which prints “<em>hello world</em>”, then the code would look like this:</p><pre>// This file would be &#39;print.go&#39; in:<br>// &lt;GOPATH&gt;/src/github.com/&lt;your-username&gt;/print</pre><pre>package print</pre><pre>import (<br>    “fmt”<br>)</pre><pre>func HelloWorld() {<br>    fmt.Println(“hello world”)<br>}</pre><p>You can now implement your print package in a Go application by importing it. Simply create a new directory within the project and do the following:</p><pre>// This file would be &#39;main.go&#39; in:<br>// &lt;GOPATH&gt;/src/github.com/&lt;your-username&gt;/print/cli</pre><pre>package main</pre><pre>import (<br>    &quot;github.com/&lt;your-username&gt;/print&quot;<br>)</pre><pre>func main() {<br>    print.HelloWorld()<br>}</pre><p>Now when you execute go run main.go on the command line, you will see “Hello world”.</p><p>This convention is very simple. It also promotes the separation of concerns. Go’s compiler will also stop you from creating cyclic dependencies. For example, if you imported your command line application’s package into the print package, Go would not allow you to compile the resulting code. This is very helpful when writing several libraries for closely related, but different APIs. The end result is reusable code that is completely compartmentalized.</p><h4>Relative imports are bad</h4><p>Even though Go really wants you to place your project in the GOPATH, you can still work outside of it using “relative imports”.</p><p><strong>Note:</strong> if you use relative imports, many of the go command’s features will no longer work with your project. This method of development is only for the Go maintainers themselves.</p><p>Regardless, if you were to move the Go project in the earlier print example outside of the GOPATH, you would find that it no longer compiles. This is because Go’s default behavior is to import packages relative to &lt;GOPATH&gt;/src directory. You can work around this by changing:</p><p>import ”github.com/&lt;your-username&gt;/print”</p><p>in ‘main.go’ to…</p><p>import “../print”</p><p>Now you can compile your application without putting it in the GOPATH!</p><p>Again, this is not the intended way to develop a Go application. I only mention it so that you do not make the same mistake I did initially, and create everything outside of the GOPATH.</p><h4>Targeting dependencies is simple, but basic</h4><p>As mentioned previously, Go has a very simple dependency management scheme:</p><p>go get a package -&gt; import the package -&gt; write some code -&gt; repeat</p><p>This is fantastic for small teams and applications. You may be asking “well, how do I target a specific version of the code?” As of Go version 1.9, the answer is you do not.</p><p>Similar to <a href="http://nvie.com/posts/a-successful-git-branching-model/">Git Flow</a>, Go assumes that all code in the default branch of a repository is “stable” — tested and deployed to production. As a result, Go does not let you specify a version (i.e., a Git tag) to use with the go get command. You can still do git checkout &lt;tag&gt; in the Go project’s directory, but that is a separate step outside of go get.</p><p>There are plans to integrate a tool named “<a href="https://github.com/golang/dep">go dep</a>” into Go. At the time of writing this piece, go dep is not included with Go.</p><h3>The shiny stuff</h3><p>While Go has its share of nuances, it also has a handful of self-selling features. I will discuss some of my favorites in this section.</p><h4>Cross compilation</h4><p>Compiling an application for different operating systems and architectures is fast, and easy to do in Go. This can be accomplished several ways. I have found that the quickest and easiest is using <a href="https://github.com/mitchellh/gox">Mitchell Hashimoto’s “gox</a>” command line tool. It wraps the go commands used to build an application for Go’s many supported operating systems. Since the tool is also a Go application, it can be downloaded by executing go get github.com/mitchellh/gox.</p><p><strong>Note</strong>: You must add &lt;GOPATH&gt;/bin to your PATH variable. If you do not do this, you will need to execute ~/go/bin/gox to use it.</p><p>After installing gox, you can compile your application for all supported operating systems by executing:</p><pre>$ cd &lt;project-directory&gt;<br>$ gox</pre><p>You can target a specific operating system as follows:</p><pre>$ gox -os &#39;windows&#39;</pre><p>And if you desire a specific architecture:</p><pre>$ gox -osarch &#39;windows/amd64&#39;</pre><p>A full list of supported operating systems (known as GOOS) and architectures (GOARCH) can be found in the <a href="https://golang.org/doc/install/source#environment">Golang Environment documentation</a>.</p><p>Lastly, you can specify an output directory and executable name:</p><pre>$ gox -output=/tmp/my-app</pre><p>The resulting artifacts’ names can be supplemented with the OS name and architecture by adding specifiers that gox recognizes:</p><pre>$ gox -output=/tmp/my-app-{{.OS}}-{{.Arch}}</pre><h4>Interfaces</h4><p>Interfaces are a common feature in most programming languages. They will be your best friends if you plan to deploy to multiple operating systems. Being able to cleanly separate implementations of your logic is very important for maintainability and readability in those cases. Using interfaces will help prevent <a href="https://en.wikipedia.org/wiki/Side_effect_(computer_science)">unforeseen side effects</a> that tend to result from an unorganized codebase.</p><p>Suppose you are creating an application that needs to manage a machine’s power state. A switch statement works relatively well for a single function:</p><pre>// power.go (revision 1/3)</pre><pre>package power</pre><pre>import (<br>    &quot;runtime&quot;<br>)</pre><pre>func Shutdown() error {<br>    switch runtime.GOOS {<br>        case &quot;darwin&quot;:<br>            // macOS logic.<br>        case &quot;linux&quot;:<br>            // Linux logic.<br>        case &quot;windows&quot;:<br>            // Windows logic.<br>    }</pre><pre>    return nil<br>}</pre><p>This code quickly becomes very difficult to read when you substitute the comments for actual code. Of course, you can mitigate this by separating the logic into separate function calls. Adding additional functions to your library will only make things messy, however:</p><pre>// power.go (revision 2/3)</pre><pre>package power</pre><pre>import (<br>    &quot;runtime&quot;<br>)</pre><pre>func Restart() error {<br>    switch runtime.GOOS {<br>        case &quot;darwin&quot;:<br>            restartDarwin()<br>        case &quot;linux&quot;:<br>            restartLinux()<br>        case &quot;windows&quot;:<br>            restartWindows()<br>    }</pre><pre>    return nil<br>}</pre><pre>func restartDarwin() {<br>}</pre><pre>// Other restart functions...</pre><pre>func Shutdown() error {<br>    switch runtime.GOOS {<br>        case &quot;darwin&quot;:<br>            shutdownDarwin()<br>        case &quot;linux&quot;:<br>            shutdownLinux()<br>        case &quot;windows&quot;:<br>            shutdownWindows()<br>    }</pre><pre>    return nil<br>}</pre><pre>func shutdownDarwin() {<br>}</pre><pre>// Other shutdown functions...</pre><pre>func Sleep() error {<br>    switch runtime.GOOS {<br>        case &quot;darwin&quot;:<br>            sleepDarwin()<br>        case &quot;linux&quot;:<br>            sleepLinux()<br>        case &quot;windows&quot;:<br>            sleepWindows()<br>    }</pre><pre>    return nil<br>}</pre><pre>func sleepDarwin() {<br>}</pre><pre>// Other sleep functions...</pre><p>Instead of constantly checking the operating system, we can create different implementations and provide a single implementation to the caller using an interface. In the following example, the Power interface will act as a contract between the package, and the caller. This means that a Power object will always have the Restart(), Shutdown(), and Sleep() functions. Finally, we can provide the implementations to a caller using a public Get() function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae17bb8dafb5095f2e500de000c1f7d9/href">https://medium.com/media/ae17bb8dafb5095f2e500de000c1f7d9/href</a></iframe><h3>Another tool for the toolbox</h3><p>In the previous sections, I covered some of the most attractive features provided by the language. Without a doubt, Go makes a fantastic alternative to scripting languages. I also believe that, given enough effort, a Go library could interoperate with other programming languages using interprocess communication, or bindings.</p><p>The language is not perfect of course. Go’s project management tools are not ideal. This might make larger teams skeptical of the language. I still recommend giving Go a shot, even if you are skeptical. There are many other features that I did not discuss here, such as Go’s excellent serialization and multitasking support.</p><p>If you do not want to install Go on your system, you can still try it out in your web browser using the <a href="https://play.golang.org/">Go Playground</a>. You can also find excellent introductions to Go at the <a href="https://tour.golang.org/welcome/1">Tour of Go</a> and <a href="https://gobyexample.com/">Go by Example</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8063b017611" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dot-debug/what-is-that-golang-thing-anyways-e8063b017611">What is that Golang thing, anyways?</a> was originally published in <a href="https://medium.com/dot-debug">.debug</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Chrome in a Docker container]]></title>
            <link>https://medium.com/dot-debug/running-chrome-in-a-docker-container-a55e7f4da4a8?source=rss----9a12780e40b3---4</link>
            <guid isPermaLink="false">https://medium.com/p/a55e7f4da4a8</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[google-chrome]]></category>
            <dc:creator><![CDATA[Stephen Fox]]></dc:creator>
            <pubDate>Sat, 18 Feb 2017 20:42:31 GMT</pubDate>
            <atom:updated>2017-02-18T20:42:30.891Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVH1l0bQG2KRGY-MTNBdHQ.png" /></figure><h4>Chrome-in-a-box.</h4><p>Have you ever wanted to run Google Chrome headlessly without installing it on your system? If not, there are a few reasons to give it a try. Maybe you want to create a throw-away web session without spinning up a full virtual machine. Or, maybe you need to run tests on a web application.</p><p>This is where tools like Docker really shine. Creating a Docker image and templating containers from it is resource-light and fast. Docker images are also easily reproducible, and can make achieving “<a href="https://en.wikipedia.org/wiki/Infrastructure_as_Code">infrastructure as code</a>” a feasible reality.</p><p>Let’s give it a shot.</p><p><strong><em>Note</em></strong><em>: All of the following code can be found in my </em><a href="https://github.com/stephen-fox/chrome-docker"><em>chrome-docker</em></a><em> Git project.</em></p><h3>Identifying the building blocks</h3><p>To run a Docker container, we will need a Docker <em>image</em>. An image is a pre-built bundle that contains all of the files and software needed to do the work you are setting out to do. In our case, the Docker image will need to contain:</p><ol><li>A basic Bash script (referred to as a ‘bootstrap’ script herein) that will run our startup logic whenever a new container is created from the image</li><li>Software required to create a “virtual” display to view Google Chrome</li><li>Google Chrome</li></ol><p>Since creating a virtual display is not unique to Docker, we can start there and figure out our dependencies along the way.</p><h3>Writing a bootstrap script</h3><p>By default, a Docker container does nothing when it is started. To actually <em>do something</em>, we will need to execute some logic whenever a new container is created from the image. Before we build the Docker image, let’s consider what we will need to run a graphical application:</p><ol><li>A X server</li><li>A window manager</li><li>A means to access the container’s display</li></ol><h4>No display? No fear!</h4><p>Our first major challenge is the lack of display. This is where Xvfb (<a href="https://www.x.org/archive/X11R7.6/doc/man/man1/Xvfb.1.xhtml">X Virtual FrameBuffer</a>) comes in <em>very</em> helpful. Per its man page:</p><blockquote><em>Xvfb</em> is an X server that can run on machines with no display hardware and no physical input devices. It emulates a dumb framebuffer using virtual memory.</blockquote><p>Since all of our container’s startup logic will need to run in a single script, we will need to start Xvfb in the background. Something to keep in mind when running anything in the background (Bash background job, or not) is whether or not subsequent operations will need to wait until the first background operation reaches a certain state. In our case, we need our X server to be fully up and running before starting a window manager.</p><p>Using the xdpyinfo utility, we can block until the X server is ready. Let’s put it all into a Bash function:</p><pre>launch_xvfb() {<br>    # Set defaults if the user did not specify envs.<br>    export DISPLAY=${XVFB_DISPLAY:-:1}<br>    local screen=${XVFB_SCREEN:-0}<br>    local resolution=${XVFB_RESOLUTION:-1280x1024x24}<br>    local timeout=${XVFB_TIMEOUT:-5}</pre><pre>    # Start and wait for either Xvfb to be fully up,<br>    # or we hit the timeout.<br>    Xvfb ${DISPLAY} -screen ${screen} ${resolution} &amp;<br>    local loopCount=0<br>    until xdpyinfo -display ${DISPLAY} &gt; /dev/null 2&gt;&amp;1<br>    do<br>        loopCount=$((loopCount+1))<br>        sleep 1<br>        if [ ${loopCount} -gt ${timeout} ]<br>        then<br>            echo &quot;[ERROR] xvfb failed to start.&quot;<br>            exit 1<br>        fi<br>    done<br>}</pre><h4>Running a window manager</h4><p>Now we have a display — but no window manager. A fantastic solution for this is the light-weight Fluxbox window manager. Similar to our Xvfb logic, we can block until Fluxbox is ready by using the wmctrl utility:</p><pre>launch_window_manager() {<br>    local timeout=${XVFB_TIMEOUT:-5}</pre><pre>    # Start and wait for either fluxbox to be fully up or we hit<br>    # the timeout.<br>    fluxbox &amp;<br>    local loopCount=0<br>    until wmctrl -m &gt; /dev/null 2&gt;&amp;1<br>    do<br>        loopCount=$((loopCount+1))<br>        sleep 1<br>        if [ ${loopCount} -gt ${timeout} ]<br>        then<br>            echo &quot;${G_LOG_E} fluxbox failed to start.&quot;<br>            exit 1<br>        fi<br>    done<br>}</pre><h4>Accessing the virtual display</h4><p>We will need a way to access the display. A creative solution is to use a VNC server. This can be especially helpful for debugging a container running on a remote system. At this point in the script, we will want to keep the Docker container running as long as the VNC server stays alive:</p><pre>run_vnc_server() {<br>    local passwordArgument=&#39;-nopw&#39;</pre><pre>    if [ -n &quot;${VNC_SERVER_PASSWORD}&quot; ]<br>    then<br>        local passwordFilePath=&quot;${HOME}/x11vnc.pass&quot;<br>        if ! x11vnc -storepasswd &quot;${VNC_SERVER_PASSWORD}&quot; &quot;${passwordFilePath}&quot;<br>        then<br>            echo &quot;[ERROR] Failed to store x11vnc password.&quot;<br>            exit 1<br>        fi<br>        passwordArgument=-&quot;-rfbauth ${passwordFilePath}&quot;<br>        echo &quot;[INFO] The VNC server will ask for a password.&quot;<br>    else<br>        echo &quot;[WARN] The VNC server will NOT ask for a password.&quot;<br>    fi</pre><pre>    x11vnc -display ${DISPLAY} -forever ${passwordArgument} &amp;<br>    wait $!<br>}</pre><h4>Bringing the bootstrap logic together</h4><p>We can bring our Bash logic together now, along with some minor tweaks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a21f39a2a8ff072df19f6e9547a72de/href">https://medium.com/media/1a21f39a2a8ff072df19f6e9547a72de/href</a></iframe><h3>Creating the Docker image</h3><p>With the bootstrap script completed, we can focus on actually creating the Docker image. This is accomplished by creating a plain text file named Dockerfile. It instructs Docker what to do when building the image.</p><p>Docker images have a selectable starting point. Since Ubuntu supports Chrome out of the box, we will use the ubuntu:trusty image as ours. It is important that we update apt-get too — otherwise, we will not be able to install any new packages:</p><pre>FROM ubuntu:trusty</pre><pre>RUN apt-get update; apt-get clean</pre><p>We will also want to add a user for running Chrome, since running as root is not allowed by Chrome:</p><pre># Add a user for running applications.<br>RUN useradd apps<br>RUN mkdir -p /home/apps &amp;&amp; chown apps:apps /home/apps</pre><p>Now we can install required tools, including fluxbox, wmctrl, x11vnc, and xvfb. We will also install wget so we can add the Google signing key to apt-get:</p><pre># Install x11vnc.<br>RUN apt-get install -y x11vnc</pre><pre># Install xvfb.<br>RUN apt-get install -y xvfb</pre><pre># Install fluxbox.<br>RUN apt-get install -y fluxbox</pre><pre># Install wget.<br>RUN apt-get install -y wget</pre><pre># Install wmctrl.<br>RUN apt-get install -y wmctrl</pre><pre># Set the Chrome repo.<br>RUN wget -q -O - <a href="https://dl-ssl.google.com/linux/linux_signing_key.pub">https://dl-ssl.google.com/linux/linux_signing_key.pub</a> | apt-key add - \<br>    &amp;&amp; echo &quot;deb <a href="http://dl.google.com/linux/chrome/deb/">http://dl.google.com/linux/chrome/deb/</a> stable main&quot; &gt;&gt; /etc/apt/sources.list.d/google.list</pre><pre># Install Chrome.<br>RUN apt-get update &amp;&amp; apt-get -y install google-chrome-stable</pre><p>Lastly, we need to copy the bootstrap script into the image and tell Docker to run the script when a new container is created from it:</p><pre>COPY bootstrap.sh /</pre><pre>CMD &#39;/bootstrap.sh&#39;</pre><h4>Bringing together the Dockerfile</h4><p>Now we can piece together our Docker commands. Make sure to name the file Dockerfile. If you specify a different name, then you will need to explicitly identify it to Docker at build time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d22817bed8d72d4ed8e3450903bd01d/href">https://medium.com/media/9d22817bed8d72d4ed8e3450903bd01d/href</a></iframe><h3>Building the Docker image</h3><p>With the Dockerfile complete, we can now build an image. This is done using the docker build command. This command will assume that the Dockerfile is actually named ‘Dockerfile’ and is in the current working directory. It takes two arguments:</p><ol><li>A unique name for the image, referred to as a “tag”</li><li>The path to copy into the “build context”. <strong>Be very careful to never specify ‘/’. Doing so will copy your entire machine into the build context!</strong></li></ol><p>To build the Docker image, make sure the bootstrap script (named bootstrap.sh) and the Dockerfile are in the same directory and execute the following command:</p><pre>docker build -t local/chrome:0.0.1 .</pre><p>After a few minutes, Docker will finish building the image. Running docker images will show you the image name and ID.</p><p><strong><em>Note</em></strong><em>: If you are looking at my </em><a href="https://github.com/stephen-fox/chrome-docker"><em>chrome-docker repository</em></a><em>, I have automated the build command using an included Gradle project. Building it using Gradle is completely optional; it is only for convenience.</em></p><h3>Running the Docker container</h3><p>Finally, we can create and run a Docker container from the image. Go ahead and give the following command a try:</p><pre>docker run -p 5900:5900 -e VNC_SERVER_PASSWORD=password --user apps --privileged local/chrome:0.0.1</pre><p>This will launch a new Docker container and run Xvfb, Fluxbox, and a VNC server. You can access the container’s display by pointing a VNC client to 127.0.0.1.</p><p><strong><em>Note</em></strong><em>: While the </em><em>VNC_SERVER_PASSWORD argument is optional, it is not if you are using the macOS VNC viewer. If you do not set a password on macOS, you will not be able to connect to the container’s VNC server.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOr8aXoOgJf1jRG5ZlOqFg.png" /></figure><p>You can now start Chrome by right clicking the desktop and selecting:</p><pre>Applications &gt; Network &gt; Web Browsing &gt; Google Chrome</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_AExv9jtIfCLohlOJMAD2Q.png" /></figure><p>You will be prompted to make Chrome your default browser and whether or not analytics should be sent to Google. Once you answer those questions, you will be able to browse the web using Chrome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LEWSCuO3bMpARiHppX4Bww.png" /></figure><h3>Security concerns</h3><p>Is running Google Chrome this way more secure then just running Google Chrome directly on your system? Even if it is, there are a few concerns that should not be ignored:</p><ol><li>You are accessing the container using VNC. If you are not running a firewall on your machine (or the Docker host), then anyone can potentially watch you browse the web</li><li>Google Chrome requires that the --privileged Docker flag be specified. This disables security labeling for the container</li></ol><h3>Conclusion</h3><p>Is it possible to run Google Chrome in a Docker container? Yes! Should you do it for testing? Yes! Should you do it to establish a secure browsing session? You can — just make sure you are running a firewall on your machine.</p><p>Most of this code can be reused to run other graphical applications in a Docker container. So, why stop at Google Chrome?</p><p>Have fun!</p><p><strong><em>Note</em></strong><em>: All of the following code can be found in my </em><a href="https://github.com/stephen-fox/chrome-docker"><em>chrome-docker</em></a><em> Git project.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a55e7f4da4a8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dot-debug/running-chrome-in-a-docker-container-a55e7f4da4a8">Running Chrome in a Docker container</a> was originally published in <a href="https://medium.com/dot-debug">.debug</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The perils of Bash ‘eval’]]></title>
            <link>https://medium.com/dot-debug/the-perils-of-bash-eval-cc5f9e309cae?source=rss----9a12780e40b3---4</link>
            <guid isPermaLink="false">https://medium.com/p/cc5f9e309cae</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[information-security]]></category>
            <dc:creator><![CDATA[Stephen Fox]]></dc:creator>
            <pubDate>Thu, 02 Feb 2017 05:16:06 GMT</pubDate>
            <atom:updated>2017-02-02T05:22:55.413Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2eDvEhv6Dr_-xgidaRaPEQ.png" /><figcaption><em>The fateful moments aboard the Death Star prior to the power system running ‘eval’ against unsanitized user input. (Image credit: </em><a href="http://lucasfilm.com/"><em>Lusasfilm Ltd.</em></a><em>)</em></figcaption></figure><h4>Reflection injection.</h4><p>Bash is a “<a href="https://www.gnu.org/software/bash/manual/bash.html#What-is-a-shell_003f">macro processor that executes commands</a>”, which can be used to solve problems in what amounts to concise, self-contained, text files. While this elegance is easily recognized by operations teams and system admins, it can be lost to developers that constantly work with object oriented programming languages. In my own experience of switching back and forth between Bash and Java, I felt compelled to apply object oriented programming principles to my Bash scripts.</p><p>The result of this was generally positive. For example, it led to separating massive blobs of code into concise functions, limiting the scope of variables, and creating more flexible logic.</p><p>Ironically, implementing those principles has sometimes led to my own detriment. I am almost universally told by other developers to compact my Bash code during code reviews. This is a fair criticism. When you spend enough time in development tools like IntelliJ or Visual Studio, the IDE practically does this for you before anyone else ever lays eyes on your code. With Bash — it is just you, and a text editor.</p><p>In the never ending cat and mouse game of compacting code, you will eventually find yourself reading about the <a href="https://www.gnu.org/software/bash/manual/bashref.html#Bourne-Shell-Builtins">‘eval’ Bash builtin</a>. Unfortunately, ‘eval’ is a very sharp knife, and many developers fail to explain why, let alone warn others of its dangers.</p><p>This post will explain and show why implementing ‘eval’ in your scripts is a really bad idea.</p><h3>What is ‘eval’?</h3><p>To understand why ‘eval’ is dangerous, we must first understand what it is used for. As a tool, ‘eval’ is used to interpret (evaluate) strings into live logic. For example:</p><pre>$ eval echo hello world</pre><pre>hello world</pre><p>The command is not too dissimilar to reflection in programming. This lets you create variables dynamically at runtime. For example, you can create a variable whose name is the name of your current user:</p><pre>$ echo &quot;I am: ${root}&quot;</pre><pre>I am:</pre><pre>$ eval &#39;export $(whoami)=$(whoami)&#39;</pre><pre>$ echo &quot;I am: ${root}&quot;</pre><pre>I am: root</pre><p>When you find yourself reading about ‘eval’, it is usually because your current logic has boxed you into one of the few use cases that ‘eval’ can quickly solve. Being a Bash builtin, it is reliably available. The command is also <a href="http://www.thegeekstuff.com/2010/08/bash-shell-builtin-commands">commonly</a> <a href="http://unix.stackexchange.com/a/282639">recommended</a> <a href="http://stackoverflow.com/a/28183341">online</a>. It can even be used to execute logic that would normally require several lines of code in a single line of code. These factors make implementing ‘eval’ into your scripts a very tempting proposition.</p><p>A significant portion of ‘eval’ examples fail to describe the dangers of implementing the command into your logic. If you are lucky, developers may drop subtle hints, such as <a href="http://unix.stackexchange.com/a/222496">“use it cautiously” because it is “evil”</a>. As a Bash newbie, I can attest to weighing these vague warnings against finishing a script and moving onto the next project. Without an adequate explanation, ‘eval’ presents an easy crutch to logic that should be restructured or rewritten.</p><h3>A really bad idea</h3><p>Experienced Bash scripters will describe the outcome of implementing ‘eval’ in two different ways; a really bad idea, or consciously introducing a vulnerability into your script. While these concerns are exactly the same, neither actually <em>describe</em> why. In my opinion, an over-the-top implementation is needed to sufficiently illustrate why ‘eval’ is dangerous.</p><h4>The example</h4><p>Assume that you are looking to create a script that provides a basic, network-accessible API. The goal of the API in this example will be to manage a file named ‘file.txt’ using our own ‘update’ and ‘remove’ commands.</p><h4>Design</h4><p>The API will be accessible using HTTP on port 8080. In order to communicate with the API, users must know an “API key” (a special URL) to target. If the user does not provide a valid key, then the script will do nothing. If the user provides the key, but does not provide a valid command, then the script will do nothing. If the user provides a valid key and command, then the script will execute a command.</p><h4>Implementation</h4><p>We can use netcat (‘nc’) to listen on a port for HTTP GET requests. To make things easy, we will write the output of ‘nc’ to a file and parse the file for valid requests. I have implemented the example in a Bash script named <a href="https://github.com/stephen-fox/eval-is-a-really-bad-idea/blob/master/really-bad-idea.sh"><strong>really-bad-idea.sh</strong></a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a899e15970a72496517df1cf6e002090/href">https://medium.com/media/a899e15970a72496517df1cf6e002090/href</a></iframe><h4>Running it</h4><p>To start it, execute:</p><pre>$ ./really-bad-idea.sh</pre><pre>[INFO] netcat now listening on port 8080 as PID 768<br>[INFO] Make API calls to &#39;&lt;server-address&gt;:8080/api/a15d24c3d4b585e84862dc46df98bd2f&#39;</pre><p><strong><em>Note</em></strong><em>: You can press Control + C to stop the script gracefully.</em></p><h4>Positive use case</h4><p>First, let’s take a look at the positive use cases. You can make requests to the script using curl like so:</p><pre># Client request:<br># <strong>Note</strong>: Make sure to use the API key that the script spits out.</pre><pre>$ curl &#39;127.0.0.1:8080/api/a15d24c3d4b585e84862dc46df98bd2f/update&#39;</pre><p>… you will see the following result on the server side:</p><pre># Server result:</pre><pre>[INFO] Received API call: &#39;/api/a15d24c3d4b585e84862dc46df98bd2f/update&#39;<br>[INFO] Updating file...</pre><h4>Saving a few lines of code</h4><p>So far, the script meets the design requirements: it creates a public API that only validated users can utilize. Let’s take a look at the code again, specifically the lines that validate the API key in parse_incoming_data():</p><pre>eval local key=&quot;$(echo &quot;${line}&quot; | cut -f2 -d&#39; &#39;)&quot; \<br>    &amp;&amp; [ &quot;${key%/*}&quot; == &quot;${G_API_KEY}&quot; ] \<br>    &amp;&amp; execute_api_call &quot;${line}&quot;</pre><p>I used ‘eval’ here to declare a local variable containing the request’s URI. For context, a single HTTP call to netcat will spit out the following:</p><pre>$ nc -l 8080</pre><pre>GET /api/key/uri HTTP/1.1<br>Host: 127.0.0.1:8080<br>User-Agent: curl/7.43.0<br>Accept: */*</pre><p>Since we are interested in the /api/key/uri string, it makes sense to just use ‘cut’ to grab it since there will never be spaces in the string. The end result here is that I used ‘eval’ to save a few lines of code. Yah!</p><h4>Not yay: Why ‘eval’ is a really bad idea</h4><p><strong><em>Note</em></strong><em>: All of the following testing is done in a disposable Docker container. Be careful if you are fooling around with this script on an important machine. I am not responsible if you delete something important.</em></p><p>If you recall, ‘eval’ executes strings and can permit us some reflection-like abilities. Looking at the code, recall the control_c function that handles user shutdown gracefully:</p><pre># control_c<br># Executes logic to handle a Control + C press by the user.<br>control_c() {<br>    G_USER_REQUESTED_SHUTDOWN=0<br>    echo &#39;&#39;<br>    shutdown<br>}</pre><p>What do you think will happen if we send a ‘curl’ call containing $(control_c)? Let’s find out:</p><pre># Client request:<br>$ curl &#39;127.0.0.1:8080/$(shutdown)&#39;</pre><pre># Server result:<br>(...)<br>[ERROR] The listener has exited unexpectedly</pre><p>Ut-oh. I do not think that was in the requirements! Well, what happens if we try touching a file?</p><pre># Client request:<br>$ curl &#39;127.0.0.1:8080/$(touch${IFS}/not-good.txt)&#39;</pre><pre># Server result:<br>$ ls -ltr /</pre><pre>total 72<br>drwxr-xr-x   2 root root  4096 Nov  5 15:38 srv<br>drwxr-xr-x   2 root root  4096 Nov  5 15:38 opt<br>drwxr-xr-x   2 root root  4096 Nov  5 15:38 mnt<br>(...)<br>drwxrwxrwt   7 root root  4096 Feb  2 02:32 tmp<br>-rwxr-xr-x   1 root root  4163 Feb  2 02:34 really-bad-idea.sh<br>-rw-r--r--   1 root root     0 Feb  2 04:06 not-good.txt</pre><p>As you can imagine, we can do some comical things like make the script delete itself:</p><pre># Client request:<br>$ curl &#39;127.0.0.1:8080/$(rm${IFS}${PWD}/*.sh)&#39;</pre><pre># Server result:<br>$ ls /really-bad-idea.sh</pre><pre>ls: /really-bad-idea.sh: No such file or directory</pre><p>While we are removing things we do not want, let’s delete the file system:</p><pre># <strong>WARNING</strong>: THE FOLLOWING COMMAND WILL DELETE YOUR COMPUTER. DO NOT RUN THIS UNLESS YOU ARE IN A TEST ENVIRONMENT.</pre><pre># Client request:<br>$ curl &#39;127.0.0.1:8080/$(rm${IFS}-rf${IFS}/*)&#39;</pre><pre># Server result:<br>(...)<br>[INFO] Make API calls to &#39;&lt;server-address&gt;:8080/api/104d01cba6f4b74051901ca500a2650a&#39;<br>rm: cannot remove &#39;/dev/console&#39;: Device or resource busy<br>rm: cannot remove &#39;/dev/shm&#39;: Device or resource busy<br>rm: cannot remove &#39;/dev/mqueue&#39;: Device or resource busy<br>rm: cannot remove &#39;/dev/pts/ptmx&#39;: Operation not permitted<br>rm: cannot remove &#39;/etc/hosts&#39;: Device or resource busy<br>rm: cannot remove &#39;/etc/resolv.conf&#39;: Device or resource busy<br>rm: cannot remove &#39;/etc/hostname&#39;: Device or resource busy<br>rm: cannot remove &#39;/proc/fb&#39;: Operation not permitted<br>(...)<br>./really-bad-idea.sh: line 48: /tmp/listener.log: No such file or directory<br>./really-bad-idea.sh: line 54: /usr/bin/sleep: No such file or directory<br>./really-bad-idea.sh: line 48: /tmp/listener.log: No such file or directory<br>./really-bad-idea.sh: line 54: /usr/bin/sleep: No such file or directory<br>(...)</pre><h3>Closing arguments</h3><p>Bash provides a powerful toolbox full of sharp knives. The ‘eval’ command is just one of those knives. If you must absolutely use Bash in a sensitive environment, please make sure you do everything possible to either isolate it from user input or sanitize the user input first.</p><p>Whatever you do, do not use ‘eval’ unless you want to end up like my Docker containers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc5f9e309cae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dot-debug/the-perils-of-bash-eval-cc5f9e309cae">The perils of Bash ‘eval’</a> was originally published in <a href="https://medium.com/dot-debug">.debug</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing Gradle]]></title>
            <link>https://medium.com/dot-debug/installing-gradle-c4baf7bb0f11?source=rss----9a12780e40b3---4</link>
            <guid isPermaLink="false">https://medium.com/p/c4baf7bb0f11</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Stephen Fox]]></dc:creator>
            <pubDate>Thu, 26 Jan 2017 04:21:15 GMT</pubDate>
            <atom:updated>2017-02-02T05:37:23.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUoY-Na_N3s4HTZfcJ9r8g.png" /><figcaption>Image source: Gradle Inc. / <a href="http://crazyadmins.com/wp-content/uploads/2015/10/d.png">crazyadmins.com</a></figcaption></figure><h4>Gradlicious!</h4><p><a href="https://gradle.org/">Gradle</a> is a fantastic build automation tool, capable of building everything from Java to iOS applications.</p><p>Installing Gradle can be intimidating if you are not familiar with the command line. In this post, I will outline how to install it on several platforms.</p><p><strong><em>Note</em></strong><em>: This guide is not the final word on how to install Gradle. Some aspects can be changed to your liking.</em></p><h3>Step 1. Download Gradle</h3><h4>Via a web browser</h4><p>You can <a href="https://gradle.org/gradle-download/">download Gradle from here</a>. You will want the binary release, unless you want the source code and example code too. Gradle is platform agnostic; there are no operating specific downloads.</p><h4>Via the command line</h4><p>Run curl -O <a href="https://services.gradle.org/distributions/gradle-3.3-bin.zip">https://services.gradle.org/distributions/gradle-3.3-bin.zip</a></p><h3>Step 2. Install the Java Development Kit (JDK)</h3><p><a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html">Download the JDK</a> for your operating system. Installing JDK is usually very straight forward:</p><ul><li>For Windows and macOS, simply run the installer</li><li>For RedHat based Linux systems, install the .rpm</li><li>For other Linux operating systems, checkout <a href="http://askubuntu.com/a/521154">Salem’s post</a>.</li></ul><h3>Step 3. Setup Gradle</h3><p>While Gradle is platform agnostic, you still need to do some platform-specific configuration. See below for instructions specific to your operating system.</p><h4>Setup on macOS</h4><p><strong><em>Note</em></strong><em>: When I say ‘directory’, I am referring to a standard macOS ‘folder’.</em></p><ol><li>Extract the Gradle archive to your Desktop. Remember the name of the directory that is extracted from the archive, you will need it later</li><li>Open the Terminal application from the Utilities directory</li><li>Type sudo mkdir /Applications/gradle and hit enter</li><li>Type cd /Applications/gradle and hit enter</li><li>Type sudo cp -r ~/Desktop/name-of-gradle-directory . and hit enter</li><li>Type sudo ln -s name-of-gradle-directory target and hit enter</li><li>Type sudo ln -s /Applications/gradle/target/bin /usr/local/bin/gradle and hit enter</li><li>Quit and open a new Terminal. Type gradle --version to confirm it is working</li><li>You can now delete both the Gradle archive and the Gradle directory that you extracted to your Desktop</li></ol><h4>Setup on Windows</h4><p><strong><em>Note</em></strong><em>: When I say ‘directory’, I am referring to a standard Windows ‘folder’.</em></p><ol><li>Extract the Gradle archive to your Desktop. Remember the name of the directory that is extracted from the archive, you will need it later</li><li>Open a new File Explorer window and open the C:\ drive</li><li>Create a new directory named ‘gradle’ in C:\</li><li>Copy the directory you extracted from step 1. into the new ‘gradle’ directory</li><li>Open the Windows menu (the Start menu), and type ‘Command Prompt’</li><li>Right click on ‘Command Prompt’ and select ‘Run as Administrator’</li><li>Type cd C:\gradle into the Command Prompt and hit enter</li><li>Type mklink /J target name-of-gradle-directory</li><li>Open the Windows menu again, and type ‘System Environment Variables’. Open the resulting shortcut</li><li>Click the ‘Environment Variables’ button</li><li>Under the ‘System Variables’, edit the ‘Path’ variable</li><li>Click the ‘New’ button, and add C:\gradle\target\bin</li><li>Click OK to save your changes</li><li>Close the Command Prompt that we opened earlier, and open a new Command Prompt. Type gradle --version to confirm it is working</li><li>You can now delete both the Gradle archive and the Gradle directory that you extracted to your Desktop</li></ol><h4>Setup on Linux</h4><ol><li>Extract the Gradle archive to your home directory. Remember the name of the directory that is extracted from the archive, you will need it later</li><li>Open a new Terminal</li><li>Type sudo mkdir -p /opt/gradle and hit enter</li><li>Type cd /opt/gradle and hit enter</li><li>Type sudo cp -r ~/name-of-gradle-directory . and hit enter</li><li>Type sudo ln -s name-of-gradle-directory target and hit enter</li><li>Type sudo ln -s /opt/gradle/target/bin /usr/local/bin/gradle and hit enter</li><li>Close and open a new Terminal. Type gradle --version to confirm it is working</li><li>You can now delete both the Gradle archive and the Gradle directory that you extracted to your home directory</li></ol><h3>Troubleshooting</h3><h4>‘Cannot find JAVA_HOME’ or ‘JAVA_HOME is not set’</h4><p>Make sure that you have installed <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html">Oracle’s Java Development Kit</a>. After doing that, <a href="https://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/">follow these instructions</a> to set the JAVA_HOME variable.</p><h4>‘Permission denied’ or similar permissions related errors</h4><p>On macOS or Linux, make sure that you are using sudo to copy Gradle installation files around. If you are on Windows, make sure you are running the Command Prompt as an Administrator when creating symlinks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4baf7bb0f11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dot-debug/installing-gradle-c4baf7bb0f11">Installing Gradle</a> was originally published in <a href="https://medium.com/dot-debug">.debug</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying artifacts to Maven using Gradle]]></title>
            <link>https://medium.com/dot-debug/deploying-artifacts-to-maven-using-gradle-b669acc1b6f8?source=rss----9a12780e40b3---4</link>
            <guid isPermaLink="false">https://medium.com/p/b669acc1b6f8</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Stephen Fox]]></dc:creator>
            <pubDate>Thu, 26 Jan 2017 04:19:44 GMT</pubDate>
            <atom:updated>2017-01-26T13:59:31.385Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvOtz4-HAuJ_-5EKoXOiaw.png" /></figure><h4>Sometimes more is just confusing.</h4><p>Artifacts are files such as an executable or a compressed archive that are produced by a build process. When it comes time to store them somewhere, a good place to do so is a Maven artifact repository.</p><p>This can be done a number of ways — but my current favorite is to use Gradle as an interface into Maven. Gradle is a powerful build automation tool that is well documented and easy to learn. <a href="https://medium.com/@.debug/installing-gradle-c4baf7bb0f11#.viej4kcx4">See my installation post to install it</a>.</p><p><a href="https://medium.com/@.debug/installing-gradle-c4baf7bb0f11">Installing Gradle</a></p><p>Within Gradle itself, there are a few ways to deploy artifacts to a Maven; some offer finer control at the cost of boiler plate, while others will suffice for small projects. This can be overwhelming when looking at Gradle’s documentation, which describes several ways to deploy to Maven. In this post we will look at Gradle’s publish and upload tasks, and try to de-mystify them.</p><p><strong>Note</strong>: This post is based on Gradle 3.3, which at the time of writing is the current release version.</p><h3>The ‘publish’ task</h3><p>I have found the ‘<a href="https://docs.gradle.org/current/userguide/publishing_maven.html">publish</a>’ task very useful for uploading a single artifact, or uploading several artifacts all at once (which will be discussed later in this post). This task is provided by the maven-publish plugin.</p><p>Advantages:</p><ul><li>Small code footprint</li><li>Easy to read and understand at a glance</li></ul><p>Disadvantages:</p><ul><li>Gets tricky to manage and interact with as you add more artifacts</li></ul><h4>Single artifact upload using ‘publish’</h4><p>In the following example, pretend we have a file named ‘some-artifact.tar.gz’, and that we want to deploy it to a Maven repository. You will need to create the following files:</p><p><strong>build.gradle</strong></p><pre>apply plugin: &#39;maven-publish&#39;<br><br>group &#39;com.group.binaries&#39;<br>version = externalVersion<br><br>publishing {<br>    publications {<br>        maven(MavenPublication) {<br>            artifact(&#39;some-artifact.tar.gz&#39;) {<br>                extension &#39;tar.gz&#39;<br>            }<br>        }<br>    }<br>    repositories {<br>        maven {<br>            name &#39;deploy&#39;<br>            url deployRepoUrl<br>            credentials {<br>                username = deployRepoUsername<br>                password = deployRepoPassword<br>            }<br>        }<br>    }<br>}</pre><p><strong>gradle.properties</strong></p><pre>externalVersion=1.0-SNAPSHOT<br>deployRepoUrl=https://my-repo.com/maven-snapshots<br>deployRepoUsername=your-username<br>deployRepoPassword=your-password</pre><p><strong>settings.gradle</strong></p><pre>rootProject.name = &#39;some-project&#39;</pre><p>To deploy ‘some-artifact.tar.gz’, run the following command on the command line:</p><p>gradle publish</p><p>… or if you want to override settings in gradle.properties at build time:</p><p>gradle publish -PdeployRepoUsername=flying -PdeployRepoPassword=pig</p><h4>Multiple artifacts using ‘publish’</h4><p>Unfortunately, depending on what you want to do, this is where publish can get pretty clunky. If you want to deploy several artifacts at once, then that is not too bad. However, deploying several artifacts at different times requires a fair amount of code.</p><p>In the following example, assume we want to deploy ‘centos-app-x64.rpm’, ‘macos-app-x64.dmg’, and, ‘windows-app-x64.exe’. You can re-use the gradle-properties and settings.gradle files from above. But, make sure to overwrite build.gradle with the following:</p><pre>apply plugin: &#39;maven-publish&#39;<br><br>group &#39;com.group.binaries&#39;<br>version = externalVersion<br><br>publishing {<br>    publications {<br>        maven(MavenPublication) {<br>            artifact(&#39;centos-app-x64.rpm&#39;) {<br>                classifier &#39;centos-x64&#39;<br>                extension &#39;rpm&#39;<br>            }<br>            artifact(&#39;macos-app-x64.dmg&#39;) {<br>                classifier &#39;macos-x64&#39;<br>                extension &#39;dmg&#39;<br>            }<br>            artifact(&#39;windows-app-x64.exe&#39;) {<br>                classifier &#39;windows-x64&#39;<br>                extension &#39;exe&#39;<br>            }<br>        }<br>    }<br>    repositories {<br>        maven {<br>            name &quot;deploy&quot;<br>            url deployRepoUrl<br>            credentials {<br>                username = deployRepoUsername<br>                password = deployRepoPassword<br>            }<br>        }<br>    }<br>}</pre><p>Now, when you execute gradle publish, all three artifacts will be uploaded at the same time. For most projects, this will suffice just fine. However, there might be times where you only want to deploy a single artifact at a time. While it is possible to accomplish that using ‘publish’, I find the ‘upload’ task to be better suited to managing multiple artifacts.</p><h3>The ‘upload’ task</h3><p>The ‘<a href="https://docs.gradle.org/current/userguide/maven_plugin.html">upload</a>’ task is quirky. It is also a bit overkill if you only need to work with a single artifact. That said, it will give you more control down the road if you decide to deploy multiple artifacts. This task is provided by the maven plugin.</p><p>Advantages:</p><ul><li>Great for managing multiple artifacts</li><li>Easy to interact with on the command line</li></ul><p>Disadvantages:</p><ul><li>A lot of boiler plate if you only have one artifact</li><li>Big code footprint</li><li>Strange configuration (if you are not familiar with it)</li></ul><h4>Single artifact using ‘upload’</h4><p>Assume we have a single artifact named ‘some-artifact.tar.gz’. You will need to create the following files:</p><p><strong>build.gradle</strong></p><pre>apply plugin: &#39;maven&#39;<br><br>group &#39;com.group.binaries&#39;<br>version = externalVersion<br><br>configurations {<br>    someArtifact<br>}<br><br>artifacts {<br>    someArtifact file: file(&#39;some-artifact.tar.gz&#39;), name: &#39;some-artifact&#39;, type: &#39;tar.gz&#39;<br>}<br><br>uploadSomeArtifact {<br>    description &#39;Uploads some artifact.&#39;<br>    group &#39;publishing&#39;<br>    repositories {<br>        mavenDeployer {<br>            repository(url: deployRepoUrl) {<br>                authentication(userName: deployRepoUsername, password: deployRepoPassword)<br>            }<br>        }<br>    }<br>}</pre><p><strong>gradle.properties</strong></p><pre>externalVersion=1.0-SNAPSHOT<br>deployRepoUrl=https://my-repo.com/maven-snapshots<br>deployRepoUsername=your-username<br>deployRepoPassword=your-password</pre><p><strong>settings.gradle</strong></p><pre>rootProject.name = &#39;some-project&#39;</pre><p>Yeah… If you have not seen this before, you are probably wondering why there is so much boiler plate in ‘build.gradle’. First off, the name of the ‘upload’ task is <strong>very</strong> important. The task name must be called upload + NameOfTheTargetConfiguration. This is how Gradle figures out which configuration to apply to the upload task. A configuration is an object Gradle provides us to define artifacts and their attributes. In this example, we created one called someArtifact. Once a configuration is created in the configurations closure, we can then define the artifact for someArtifact using the artifacts closure.</p><p>Now, to deploy ‘some-artifact.tar.gz’, execute:</p><p>gradle uploadSomeArtifact</p><p>… or if you want to override settings in gradle.properties at build time:</p><p>gradle uploadSomeArtifact -PdeployRepoUsername=flying -PdeployRepoPassword=pig</p><h4>Multiple artifacts using ‘upload’</h4><p>Assume we want to upload ‘centos-app-x64.rpm’, ‘macos-app-x64.dmg’, and, ‘windows-app-x64.exe’. You can re-use the gradle-properties and settings.gradle files from above. But, make sure to overwrite build.gradle with the following:</p><pre>apply plugin: &#39;maven&#39;<br><br>group &#39;com.group.binaries&#39;<br>version = externalVersion<br><br>configurations {<br>    centos_x64<br>    macos_x64<br>    windows_x64<br>}<br><br>artifacts {<br>    centos_x64 file: file(&#39;centos-app-x64.rpm&#39;), name: &#39;my-app&#39;, type: &#39;rpm&#39;, classifier: &#39;x64&#39;<br>    macos_x64 file: file(&#39;macos-app-x64.rpm&#39;), name: &#39;my-app&#39;, type: &#39;dmg&#39;, classifier: &#39;x64&#39;<br>    windows_x64 file: file(&#39;windows-app-x64.rpm&#39;), name: &#39;my-app&#39;, type: &#39;exe&#39;, classifier: &#39;x64&#39;<br>}<br><br>uploadCentos_x64 {<br>    description &#39;Uploads the CentOS 64-bit application.&#39;<br>    group &#39;publishing&#39;<br>    repositories {<br>        mavenDeployer {<br>            repository(url: deployRepoUrl) {<br>                authentication(userName: deployRepoUsername, password: deployRepoPassword)<br>            }<br>        }<br>    }<br>}</pre><pre>uploadMacos_x64 {<br>    description &#39;Uploads the macOS 64-bit application.&#39;<br>    group &#39;publishing&#39;<br>    repositories {<br>        mavenDeployer {<br>            repository(url: deployRepoUrl) {<br>                authentication(userName: deployRepoUsername, password: deployRepoPassword)<br>            }<br>        }<br>    }<br>}</pre><pre>uploadWindows_x64 {<br>    description &#39;Uploads the Windows 64-bit application.&#39;<br>    group &#39;publishing&#39;<br>    repositories {<br>        mavenDeployer {<br>            repository(url: deployRepoUrl) {<br>                authentication(userName: deployRepoUsername, password: deployRepoPassword)<br>            }<br>        }<br>    }<br>}</pre><p>Yes, this is a lot more code than ‘publish’. But, the key difference is that we can now deploy our artifacts independently of one another. In other words, if I want to only deploy the Windows application, I can do so by running:</p><p>gradle uploadWindows_x64</p><p>Uploading multiple artifacts at the same time is still possible, just run:</p><p>gradle uploadCentos_x64 uploadMacos_x64 uploadWindows_x64</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b669acc1b6f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dot-debug/deploying-artifacts-to-maven-using-gradle-b669acc1b6f8">Deploying artifacts to Maven using Gradle</a> was originally published in <a href="https://medium.com/dot-debug">.debug</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>