<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Karl Fischer</title>
    <description>A tech-blog about programming, automation and deployment.
</description>
    <link>http://fishi0x01.devtail.com/</link>
    <atom:link href="http://fishi0x01.devtail.com/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Sun, 05 Jul 2026 10:51:31 +0000</pubDate>
    <lastBuildDate>Sun, 05 Jul 2026 10:51:31 +0000</lastBuildDate>
    <generator>Jekyll v3.10.0</generator>
    
      <item>
        <title>Measuring Traffic with iptables</title>
        <description>&lt;p class=&quot;text-justify&quot;&gt;I recently read about a neat method of measuring traffic with iptables on linux hosts, which is nice for pentesting or infrastructure debugging. 
This is a rather short post describing that approach.&lt;/p&gt;
&lt;!--more--&gt;

&lt;h2 id=&quot;benefits-of-using-iptables-for-traffic-measurements&quot;&gt;Benefits of using iptables for traffic measurements&lt;/h2&gt;

&lt;ol class=&quot;text-justify&quot;&gt;
  &lt;li&gt;One nice thing about &lt;a href=&quot;https://en.wikipedia.org/wiki/Iptables&quot;&gt;iptables&lt;/a&gt; is that it is very likely to be present on any linux server/client you run, so you dont need to install any extra packages.&lt;/li&gt;
  &lt;li&gt;For infrastructure debugging/planning purposes you might need to know quickly how much traffic flows between 2 specific hosts/ports/… . Maybe you do not have monitoring in place yet or the monitoring is not fine grained enough (e.g., aggregating ALL packets on host interfaces).&lt;/li&gt;
  &lt;li&gt;In pentesting this is a fast and easy method to measure how much traffic/attention your operation produces.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;hands-on-example&quot;&gt;Hands-on Example&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Let us assume we want to quickly measure the traffic between the current machine and a remote host.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Initially, we have empty iptables chains:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;
~# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;Of course some servers might already have rules attached and we do not want to mess with them. 
We create a new chain dedicated for our measurements:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;
~# iptables -N TARGET
~# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

Chain TARGET (0 references)
target     prot opt source               destination
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;Now we attach measurement rules. 
We want to measure traffic between the current server and the machine 10.11.1.227 in our local network:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;
~# iptables -A TARGET -d 10.11.1.227
~# iptables -A TARGET -s 10.11.1.227
~# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

Chain TARGET (0 references)
target     prot opt source               destination         
           all  --  anywhere             10.11.1.227         
           all  --  10.11.1.227          anywhere
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;Next, we attach the new chain to input and output chains:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;
~# iptables -A INPUT -j TARGET
~# iptables -A OUTPUT -j TARGET
~# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
TARGET     all  --  anywhere             anywhere            

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         
TARGET     all  --  anywhere             anywhere            

Chain TARGET (2 references)
target     prot opt source               destination         
           all  --  anywhere             10.11.1.227         
           all  --  10.11.1.227          anywhere
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;Now everything is in place. 
We can finally zero the packet and byte counters, trigger a command to produce traffic and verify that the traffic was counted:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;
~# iptables -Z
~# nmap -nA 10.11.1.227
..snip..
~# iptables -L TARGET -n -v -x
Chain TARGET (2 references)
    pkts      bytes target     prot opt in     out     source               destination         
    4663   353156            all  --  *      *       0.0.0.0/0            10.11.1.227         
    3061   214887            all  --  *      *       10.11.1.227          0.0.0.0/0
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;We clearly see how many packets and bytes were transferred between the current server and 10.11.1.227.&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;&lt;strong&gt;NOTE:&lt;/strong&gt; Using &lt;a href=&quot;https://en.wikipedia.org/wiki/Nmap&quot;&gt;nmap&lt;/a&gt; for port scanning is illegal in most countries. 
Use it only on networks that you own or for which you have explicit scanning permissions from the owner.&lt;/p&gt;
&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;After we are done we can cleanup:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;
~# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
TARGET     all  --  anywhere             anywhere            

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         
TARGET     all  --  anywhere             anywhere            

Chain TARGET (2 references)
target     prot opt source               destination         
           all  --  anywhere             10.11.1.227         
           all  --  10.11.1.227          anywhere            
~# iptables -D INPUT 1
~# iptables -D OUTPUT 1
~# iptables -F TARGET 
~# iptables -X TARGET 
~# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;Finally, here is a short script for setting up the chains and rules to measure traffic between 2 hosts:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;measureTraffic.sh&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/47bf14940e08650374ef9501e71feb5d.js?file=measureTraffic.sh&quot;&gt; &lt;/script&gt;&lt;/p&gt;

</description>
        <pubDate>Sat, 30 Mar 2019 10:30:00 +0000</pubDate>
        <link>http://fishi0x01.devtail.com/weblog/2019/03/30/measuring-traffic-with-iptables/</link>
        <guid isPermaLink="true">http://fishi0x01.devtail.com/weblog/2019/03/30/measuring-traffic-with-iptables/</guid>
        
        
        <category>tooling</category>
        
      </item>
    
      <item>
        <title>Jenkins-as-Code Part III | JobDSL</title>
        <description>&lt;p class=&quot;text-justify&quot;&gt;The 3rd part of the Jenkins-as-Code series focuses on the automated creation of &lt;a href=&quot;/weblog/2019/01/06/jenkins-as-code-part-1/#job-interface&quot;&gt;job interfaces&lt;/a&gt;. 
That could be achieved with pure groovy scripting as used in the &lt;a href=&quot;/weblog/2019/01/12/jenkins-as-code-part-2/&quot;&gt;previous part&lt;/a&gt;. 
However, the &lt;a href=&quot;https://plugins.jenkins.io/job-dsl&quot;&gt;JobDSL plugin&lt;/a&gt; offers a more convenient and clean way, so we will focus on that.&lt;/p&gt;
&lt;!--more--&gt;

&lt;p class=&quot;text-justify&quot;&gt;There are already quite a lot of tutorials and code snippets about the JobDSL plugin all over the web, so this will be a rather short post. 
I post this merely for the sake of completion as without JobDSL, Jenkins is not fully as-code.
The complete code can be found in this &lt;a href=&quot;https://github.com/devtail/jenkins-as-code&quot;&gt;demo repo&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;jobdsl-introduction&quot;&gt;JobDSL Introduction&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;JobDSL is a DSL language on top of groovy. 
It offers an easy way to describe job interfaces as-code. 
It is very common to have a job interface seeding pipeline, which pulls the jobDSL code from a repository and provisions the job interfaces. 
Jenkins jobDSL is very easy to understand and write. 
It is easy to pickup as it comes with a &lt;a href=&quot;https://jenkinsci.github.io/job-dsl-plugin/&quot;&gt;good documentation&lt;/a&gt;. 
However, jobDSL can only provision features of plugins that are already installed in your jenkins instance. 
So the online documentation might show you features which are not available to your jenkins instance because of missing plugins. 
You can find all available features documented on your jenkins instance at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;${JENKINS_BASE_URL}/plugin/job-dsl/api-viewer/index.html&lt;/code&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Further, there is an online &lt;a href=&quot;http://job-dsl.herokuapp.com/&quot;&gt;playground for jobDSL&lt;/a&gt; scripts. 
It translates your scripts to the final xml of the job interface, so it is ideal to quickly validate your scripts during jobDSL development.&lt;/p&gt;

&lt;h2 id=&quot;multibranch-build-pipelines&quot;&gt;Multibranch Build Pipelines&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;After all that praise, now let’s have a look at some code. 
In the following we create a set of Multibranch Pipelines for project repositories on Github:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;multibranchJobs.groovy:&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/4ac66ebeb096c163b03d46bc1e2ec89b.js?file=multibranchJobs.groovy&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;We assume that Jenkins is already hooked up with Github, which is a requirement for a Github Multibranch pipeline to function.&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;Hooking up your Jenkins instance with Github and setting up credentials for CI users can be done fully as-code as well, as we have seen in the &lt;a href=&quot;/weblog/2019/01/12/jenkins-as-code-part-2/&quot;&gt;previous part&lt;/a&gt; of this series.&lt;/p&gt;
&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;A seed pipeline to trigger the jobDSL could look like that:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;seedPipeline.groovy:&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/4ac66ebeb096c163b03d46bc1e2ec89b.js?file=seedPipeline.groovy&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;This is a very simplified seeding pipeline. In the &lt;a href=&quot;/weblog/2019/01/12/jenkins-as-code-part-2/&quot;&gt;previous part&lt;/a&gt; of this series we covered a more mature configuration and seeding pipeline.&lt;/p&gt;
&lt;/div&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;This short post gave a quick overview of the JobDSL plugin and how to use it. 
We created a simple DSL for multibranch pipeline job interfaces of different projects hosted on Github.&lt;/p&gt;

</description>
        <pubDate>Sat, 09 Feb 2019 10:30:00 +0000</pubDate>
        <link>http://fishi0x01.devtail.com/weblog/2019/02/09/jenkins-as-code-part-3/</link>
        <guid isPermaLink="true">http://fishi0x01.devtail.com/weblog/2019/02/09/jenkins-as-code-part-3/</guid>
        
        
        <category>jenkins</category>
        
      </item>
    
      <item>
        <title>Jenkins-as-Code Part II | Configuration</title>
        <description>&lt;p class=&quot;text-justify&quot;&gt;This is the 2nd part of the Jenkins-as-Code series. 
In this part we will focus on configuring Jenkins through code. 
The goal is to avoid manual configuration in the UI and instead 
leverage the configuration as code plugin and configuration scripts 
in a central Github repository which are executed by a Jenkins pipeline.&lt;/p&gt;
&lt;!--more--&gt;

&lt;p class=&quot;text-justify&quot;&gt;In the &lt;a href=&quot;/weblog/2019/01/06/jenkins-as-code-part-1/&quot;&gt;previous part&lt;/a&gt; of this series we created a Jenkins 
docker image with a baked in configuration pipeline.&lt;br /&gt;
We now focus on the components of that pipeline, i.e., 
running the &lt;a href=&quot;/weblog/2019/01/06/jenkins-as-code-part-1/#casc&quot;&gt;CasC&lt;/a&gt; plugin, 
executing &lt;a href=&quot;/weblog/2019/01/06/jenkins-as-code-part-1/#configuration-script&quot;&gt;configuration scripts&lt;/a&gt; 
and &lt;a href=&quot;/weblog/2019/01/06/jenkins-as-code-part-1/#seeding&quot;&gt;seeding&lt;/a&gt; job interfaces. 
The complete code can be found in this &lt;a href=&quot;https://github.com/devtail/jenkins-as-code&quot;&gt;demo repo&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;directory-layout&quot;&gt;Directory Layout&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Lets quickly remind ourselves about the layout of our shared library repository.&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;shared-library
|-- resources
|   |-- config
|   |   |-- configuration-as-code-plugin
|   |   |   `-- jenkins.yaml
|   |   `-- groovy
|   |       |-- timezone.groovy
|   |       |-- triggerConfigurationAsCodePlugin.groovy
|   |       `-- userPublicKeys.groovy
|   |-- init
|   |   `-- ConfigurationAndSeedingPipeline.groovy
|   `-- jobDSL
`-- vars
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;The majority of Jenkins can be configured using CasC, but there are a few things 
which do still require groovy system configuration scripts, like setting the timezone.&lt;/p&gt;

&lt;h2 id=&quot;configuration-as-code-plugin&quot;&gt;Configuration as Code Plugin&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Configuring Jenkins with groovy scripts can be tedious. 
You have to go through the plugin’s code, find the constructor and 
properly use it in groovy code in order to configure it.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;However, in 2018 a new approach arised in the form of a plugin. 
It is called the &lt;a href=&quot;https://plugins.jenkins.io/configuration-as-code&quot;&gt;configuration-as-code plugin&lt;/a&gt; (CasC). 
The goal of this plugin is to describe your jenkins configuration in simple &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.yaml&lt;/code&gt; files.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;The following CasC file configures Security, GitHub, OAuth, Slack, Themes, Agents and Authorizations:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;jenkins.yaml:&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/63ce90a4e5b24aa0297aa69622d8ca8f.js?file=jenkins.yaml&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Secrets are described as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;${secret}&lt;/code&gt;. As of writing this article, secrets in CasC can be loaded 
from environment variables, files or &lt;a href=&quot;https://www.vaultproject.io/&quot;&gt;HashiCorp Vault&lt;/a&gt; paths. 
In this post’s &lt;a href=&quot;https://github.com/devtail/jenkins-as-code&quot;&gt;demo repo&lt;/a&gt; we use files as secret sources. 
The path to the secret files is pre-baked in the Dockerfile as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ENV SECRETS=&quot;/var/jenkins_home/&quot;&lt;/code&gt;. 
A secret like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;${jenkins-ssh-keys/ssh-agent-access-key}&lt;/code&gt; is then loaded from CasC at
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/var/jenkins_home/jenkins-ssh-keys/ssh-agent-access-key&lt;/code&gt;. 
However, I am a big fan of HashiCorp’s Vault. Whenever possible, I use it as a secret source, but 
that is out of scope of this blog post. To setup CasC with Vault, consult their &lt;a href=&quot;https://github.com/jenkinsci/configuration-as-code-plugin&quot;&gt;README&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;configuration-scripts&quot;&gt;Configuration Scripts&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;CasC does the heavy lifting of our configuration work. However, there are some aspects that still 
need some groovy scripting magic.&lt;/p&gt;

&lt;h3 id=&quot;timezone&quot;&gt;Timezone&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;Obviously a proper timezone setting is nice in order to not be confused by the build times.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;timezone.groovy:&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/7c2d29afbaa0f16126eb4d4b35942f76.js?file=timezone.groovy&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;h3 id=&quot;user-public-keys&quot;&gt;User Public Keys&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;We can add public keys for users.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;user-public-keys.groovy:&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/7c2d29afbaa0f16126eb4d4b35942f76.js?file=userPublicKeys.groovy&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Adding a public key to a user is useful if you must interact with jenkins via &lt;a href=&quot;https://jenkins.io/doc/book/managing/cli/&quot;&gt;jenkins-cli&lt;/a&gt;. 
In my experience Jenkins CLI works best when used with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-ssh&lt;/code&gt; option.&lt;/p&gt;

&lt;h3 id=&quot;others&quot;&gt;Others&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;Over the time I gathered more configuration scripts, e.g., GitHub OAuth or Slack configuration. 
Thanks to CasC I do not need them anylonger. However, I keep the collection in a 
&lt;a href=&quot;https://gist.github.com/fishi0x01/7c2d29afbaa0f16126eb4d4b35942f76&quot;&gt;gist&lt;/a&gt;. Maybe it will still be of help to someone out there.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;We now have a fully configured Jenkins. 
The configuration is part of our shared library. 
The configuration is executed via a single pre-baked configuration and seeding pipeline 
which uses our shared library. 
We can change a configuration by pushing the change to the shared library and running 
the pre-baked configuration and seeding pipeline in Jenkins.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;In the &lt;a href=&quot;/weblog/2019/02/09/jenkins-as-code-part-3/&quot;&gt;next part&lt;/a&gt; of this series we will have a quick look at Jenkins JobDSL plugin for job interfaces as-code.&lt;/p&gt;

</description>
        <pubDate>Sat, 12 Jan 2019 14:30:00 +0000</pubDate>
        <link>http://fishi0x01.devtail.com/weblog/2019/01/12/jenkins-as-code-part-2/</link>
        <guid isPermaLink="true">http://fishi0x01.devtail.com/weblog/2019/01/12/jenkins-as-code-part-2/</guid>
        
        
        <category>jenkins</category>
        
      </item>
    
      <item>
        <title>Jenkins-as-Code Part I | Initial Setup</title>
        <description>&lt;p class=&quot;text-justify&quot;&gt;This is the beginning of a series about full Jenkins automation.
I am calling that approach &lt;a href=&quot;#jenkins-as-code&quot;&gt;jenkins-as-code&lt;/a&gt;.
The goal is to configure every aspect of Jenkins and its pipelines from a central git repository.
We will leverage groovy scripting, jobDSL and &lt;a href=&quot;https://jenkins.io/doc/book/pipeline/shared-libraries/&quot;&gt;shared libraries&lt;/a&gt; to not only codify the build/deploy pipelines (&lt;a href=&quot;https://jenkins.io/solutions/pipeline/&quot;&gt;pipeline-as-code&lt;/a&gt;), but to also bootstrap and configure Jenkins from scratch (e.g., credentials, authorization, theme and job setup).&lt;/p&gt;
&lt;!--more--&gt;

&lt;p class=&quot;text-justify&quot;&gt;The following demo shows what we have at the end of this series:&lt;/p&gt;

&lt;p&gt;&lt;br /&gt;
&lt;img src=&quot;/content-images/jenkins-bootstrap-700px.gif&quot; alt=&quot;Demo&quot; style=&quot;display: block; margin-left: auto; margin-right: auto;&quot; /&gt;
&lt;br /&gt;&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Every aspect of what is shown here can be found in full context in the &lt;a href=&quot;https://github.com/devtail/jenkins-as-code&quot;&gt;jenkins-as-code Github repository&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It is usually a good idea to have as much as possible setup in an *-as-code approach, because it offers:&lt;/p&gt;
&lt;ul class=&quot;text-justify&quot;&gt;
  &lt;li&gt;clear definitions and automation, i.e., clear state definition and reproducibility&lt;/li&gt;
  &lt;li&gt;rollouts from central servers (offers audit logs)&lt;/li&gt;
  &lt;li&gt;common software development workflows, i.e., testing, reviewing and rollouts are easier to manage&lt;/li&gt;
&lt;/ul&gt;

&lt;p class=&quot;text-justify&quot;&gt;Since Jenkins 2.x we can use pipeline-as-code approaches like &lt;a href=&quot;https://travis-ci.com/&quot;&gt;Travis&lt;/a&gt; or &lt;a href=&quot;https://circleci.com/&quot;&gt;CircleCI&lt;/a&gt; do.
However, the overall (plugin) &lt;a href=&quot;#configuration-script&quot;&gt;configuration&lt;/a&gt; and setup of &lt;a href=&quot;#job-interface&quot;&gt;job interfaces&lt;/a&gt; is not covered by pipeline-as-code.
For a complete jenkins-as-code approach we also want our configuration and
job interfaces treated as-code and be able to rollout any changes dynamically through a jenkins job
interface without the need to restart Jenkins.&lt;/p&gt;

&lt;p&gt;In the first part of this series we will discuss the basics:&lt;/p&gt;
&lt;ul class=&quot;text-justify&quot;&gt;
  &lt;li&gt;What are the layers in jenkins-as-code?&lt;/li&gt;
  &lt;li&gt;What are the relations between those layers?&lt;/li&gt;
&lt;/ul&gt;

&lt;p class=&quot;text-justify&quot;&gt;Next, we will create a Jenkins docker image packaged with a configuration/seeding job interface and pipeline definition, which uses a central shared library from GitHub to rollout configuration and &lt;a href=&quot;#seeding&quot;&gt;seeding&lt;/a&gt; changes.
Finally, we will have a closer look at contents of that central shared library.&lt;/p&gt;

&lt;h2 id=&quot;layers-and-terminology&quot;&gt;Layers and Terminology&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;In order to avoid confusion it is very important to define the different layers and terms which will be used throughout this series.&lt;/p&gt;

&lt;h4 id=&quot;jenkins-as-code&quot;&gt;Jenkins-as-Code&lt;/h4&gt;
&lt;p class=&quot;text-justify&quot;&gt;Jenkins-as-code describes an approach to codify and automate every layer of Jenkins.
In order to achieve its goal the approach leverages jobDSL, configuration and pipeline definition scripts.&lt;/p&gt;

&lt;h4 id=&quot;job-interface&quot;&gt;Job Interface&lt;/h4&gt;
&lt;p class=&quot;text-justify&quot;&gt;A job interface describes the job in the Jenkins UI.
Deep down a job interface is xml on the Jenkins master instance, usually found at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;${JENKINS_HOME}/jobs&lt;/code&gt;.
We use a job interface to declare input parameters and to trigger the job.
Preferably, a job interface is created using the Jenkins &lt;a href=&quot;https://github.com/jenkinsci/job-dsl-plugin&quot;&gt;jobDSL plugin&lt;/a&gt;.
When a job is triggered it loads the pipeline definition.&lt;/p&gt;

&lt;h4 id=&quot;pipeline-definition&quot;&gt;Pipeline Definition&lt;/h4&gt;
&lt;p class=&quot;text-justify&quot;&gt;A pipeline definition is a groovy script which is loaded by a job interface when a job is triggered.
Those groovy scripts are also known as pipeline-as-code - an approach also known from cloud CIs like Travis or CircleCI.&lt;/p&gt;

&lt;h4 id=&quot;configuration-script&quot;&gt;Configuration Script&lt;/h4&gt;
&lt;p class=&quot;text-justify&quot;&gt;A configuration script is a system groovy script, which interacts with the Jenkins eco-system to configure Jenkins and its plugins.&lt;/p&gt;

&lt;h4 id=&quot;casc&quot;&gt;CasC&lt;/h4&gt;
&lt;p class=&quot;text-justify&quot;&gt;[C]onfiguration [as] [C]ode refers to the &lt;a href=&quot;https://plugins.jenkins.io/configuration-as-code&quot;&gt;Configuration-as-Code Plugin&lt;/a&gt;.
Rather than writing configuration scripts, this plugin allows to define your configuration
in a simple .yaml syntax.&lt;/p&gt;

&lt;h4 id=&quot;jobdsl-script&quot;&gt;JobDSL Script&lt;/h4&gt;
&lt;p class=&quot;text-justify&quot;&gt;A jobDSL script is a groovy script which programmatically describes job interfaces.
It is read by the Jenkins &lt;a href=&quot;https://github.com/jenkinsci/job-dsl-plugin&quot;&gt;jobDSL plugin&lt;/a&gt; to create the job interfaces.&lt;/p&gt;

&lt;h4 id=&quot;seeding&quot;&gt;Seeding&lt;/h4&gt;
&lt;p class=&quot;text-justify&quot;&gt;Seeding refers to creating all job interfaces from a single pipeline (the seeding job).
That pipeline executes the jobDSL scripts in order to create all job interfaces.&lt;/p&gt;

&lt;h3 id=&quot;layers-and-their-interaction&quot;&gt;Layers and their Interaction&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Layers in jenkins-as-code:&lt;/strong&gt;
&lt;img src=&quot;/content-images/jenkins-as-code-layers.png&quot; alt=&quot;Layers in jenkins-as-code&quot; style=&quot;display: block; margin-left: auto; margin-right: auto; width: 80%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interaction between the layers:&lt;/strong&gt;
&lt;img src=&quot;/content-images/jenkins-as-code-layers-interaction.png&quot; alt=&quot;Layer interaction in jenkins-as-code&quot; style=&quot;display: block; margin-left: auto; margin-right: auto; width: 80%;&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;jenkins-docker-image&quot;&gt;Jenkins Docker Image&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Now that we have covered some basics, let us begin with the hands-on work and create a docker image for our Jenkins.&lt;/p&gt;

&lt;h3 id=&quot;directory-structure&quot;&gt;Directory Structure&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;We will use the following directory structure:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;docker/
|-- Dockerfile
|-- dsl
|   `-- ConfigurationAndSeedingPipelineDSL.groovy
|-- init.groovy.d
|   `-- init.groovy
`-- plugins.txt
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;The following sub-sections show the files in detail.&lt;/p&gt;

&lt;h3 id=&quot;dockerfile-and-plugins&quot;&gt;Dockerfile and Plugins&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;We want to build an image which automatically bootstraps our Jenkins with an initial job interface for configuration and seeding.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dockerfile:&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/2b33eb533deae0a78ce23b108849bfdc.js?file=Dockerfile&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;&lt;strong&gt;NOTE:&lt;/strong&gt; That Dockerfile also installs HashiCorp’s Vault. While it is not needed in this part of the series we install it anyways for later use.&lt;/p&gt;
&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;Also, we must ensure that some plugins are installed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;plugins.txt:&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/2b33eb533deae0a78ce23b108849bfdc.js?file=plugins.txt&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Most of those plugins are not necessary at this step of the series, but might come in handy later on.&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;&lt;strong&gt;NOTE:&lt;/strong&gt; Plugin versions are not pinned here as this is a demo. 
However, I recommend to pin the plugin versions inside the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;plugins.txt&lt;/code&gt; in order to have deterministic docker image builds.&lt;/p&gt;
&lt;/div&gt;

&lt;h3 id=&quot;initial-pipeline-interface&quot;&gt;Initial Pipeline Interface&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;The seed and configuration job interface is created through a jobDSL script.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ConfigurationAndSeedingPipelineDSL.groovy:&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/2b33eb533deae0a78ce23b108849bfdc.js?file=ConfigurationAndSeedingPipelineDSL.groovy&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;h3 id=&quot;initgroovyd-for-initial-setup&quot;&gt;init.groovy.d for initial setup&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;init.groovy.d&lt;/code&gt; is a directory in the jenkins home directory, which contains configuration scripts.
Configuration scripts inside that directory are executed in alphabetical order at Jenkins boot time.
This is ideal for setting up seeding and configuration job interfaces.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;init.groovy:&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/7c2d29afbaa0f16126eb4d4b35942f76.js?file=init.groovy&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;This script first adds a SSH private deploy key to Jenkins with access permissions to the shared library repository.
Further, the script creates a configuration and seed job from a jobDSL script.
That job will be used to pull the shared library from git and rollout its configuration and jobDSL definitions.&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;&lt;strong&gt;NOTE:&lt;/strong&gt; The script assumes that the SSH key is already created and mounted into the docker container. The corresponding public key must be uploaded to GitHub as a deploy key for the shared library repository in order for Jenkins to pull it.&lt;/p&gt;
&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;When you build this docker image and start the container, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;init.groovy.d&lt;/code&gt; will add your (mounted) SSH deploy key and create the configuration and seeding job interface.
When this interface is triggered, it will load the central shared library and run our pipeline defintions.&lt;/p&gt;

&lt;h2 id=&quot;shared-library-repository&quot;&gt;Shared Library Repository&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Lets have a look now at how our shared jenkins library looks like.&lt;/p&gt;

&lt;h3 id=&quot;directory-structure-1&quot;&gt;Directory Structure&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;We will use the following directory structure for our shared library:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;shared-library
|-- resources
|   |-- config
|   |   |-- configuration-as-code-plugin
|   |   |   `-- jenkins.yaml
|   |   `-- groovy
|   |       |-- timezone.groovy
|   |       |-- triggerConfigurationAsCodePlugin.groovy
|   |       `-- userPublicKeys.groovy
|   |-- init
|   |   `-- ConfigurationAndSeedingPipeline.groovy
|   `-- jobDSL
`-- vars
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vars&lt;/code&gt; directory will contain our job pipeline (build/deploy).
Those pipelines will be called from a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Jenkinsfile&lt;/code&gt; inside one of our projects, but we will focus on that in a later part of this series and can leave it empty.
Also the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;resources/jobDSL&lt;/code&gt; directory which is intended for job definitions will be left out for now.
We will come back to in a later part of this series.
For now we focus on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;resources/init&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;resources/config&lt;/code&gt; directories.
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;resources/init&lt;/code&gt; holds initial configuration and seeding pipelines which leverage scripts in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;resources/config&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;resources/jobDSL&lt;/code&gt; to configure and seed jobs.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;In addition, we need a configuration and seeding pipeline script in the shared library repository.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ConfigurationAndSeedingPipeline.groovy:&lt;/strong&gt;
&lt;script src=&quot;https://gist.github.com/fishi0x01/2b33eb533deae0a78ce23b108849bfdc.js?file=ConfigurationAndSeedingPipeline.groovy&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;The scripts loaded and executed in this job definition, e.g., &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;triggerConfigurationAsCodePlugin.groovy&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timezone.groovy&lt;/code&gt; are discussed in the &lt;a href=&quot;/weblog/2019/01/12/jenkins-as-code-part-2/&quot;&gt;next part&lt;/a&gt; of this jenkins-as-code series.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;We now have a pipeline definition for configuration and seeding.
That pipeline defintion is triggered by an initial job interface for configuration and seeding.
The initial job interface is bootstrapped by our docker image (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;init.groovy.d&lt;/code&gt;).&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;The &lt;a href=&quot;/weblog/2019/01/12/jenkins-as-code-part-2/&quot;&gt;next part&lt;/a&gt; of the jenkins-as-code series will focus on the configuration scripts, 
e.g., OAuth authentication, theming, slack and credentials.&lt;/p&gt;

</description>
        <pubDate>Sun, 06 Jan 2019 14:45:00 +0000</pubDate>
        <link>http://fishi0x01.devtail.com/weblog/2019/01/06/jenkins-as-code-part-1/</link>
        <guid isPermaLink="true">http://fishi0x01.devtail.com/weblog/2019/01/06/jenkins-as-code-part-1/</guid>
        
        
        <category>jenkins</category>
        
      </item>
    
      <item>
        <title>My Consul Service ID hunt</title>
        <description>&lt;p class=&quot;text-justify&quot;&gt;This is a rather short post about a recent annoying issue I stumbled across. 
As the title suggests I wanted to retrieve the ID of a service from a consul node. Easy as this may sound, the &lt;a href=&quot;https://www.consul.io/api/agent/service.html#service_id&quot;&gt;documentation&lt;/a&gt; is not very clear about what the service ID really looks like or how I can find it. 
(FYI: At the time of writing I was running consul &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.8.1&lt;/code&gt; and vault &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.7.0&lt;/code&gt;)&lt;/p&gt;
&lt;!--more--&gt;

&lt;p class=&quot;text-justify&quot;&gt;What actually happened: I accidentally registered my &lt;a href=&quot;https://www.vaultproject.io/&quot;&gt;vault&lt;/a&gt; server directly with the consul server nodes, but ideally it should be connected to a local consul agent instead. 
After realizing my mistake, I properly hooked up the vault node with its local consul agent. 
Besides being registered now on the correct node, the vault service was still also registered on the consul server node and marked as failing there ..
On the first view this looks like a simple problem to solve .. 
Consul offers a &lt;a href=&quot;https://www.consul.io/api/index.html&quot;&gt;HTTP API&lt;/a&gt; which you can also use to &lt;a href=&quot;https://www.consul.io/api/agent/service.html#deregister-service&quot;&gt;deregister services&lt;/a&gt; on nodes manually. 
Straight forward - or so it seems..&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;According to the documentation and assuming I can reach my consul node via localhost I just need to run:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;curl -v -X PUT http://localhost:8500/v1/agent/service/deregister/:service_id
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;But wait - what’s my &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;:service_id&lt;/code&gt;??? I figured, that my vault’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;:service_id&lt;/code&gt; might as well be the name of the service itself: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vault&lt;/code&gt;. 
It didn’t work:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ curl -sX PUT http://localhost:8500/v1/agent/service/deregister/vault
Unknown service &quot;vault&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;Seems &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vault&lt;/code&gt; is really just a service name and not a proper service id. 
My failing vault service is still showing up inside the consul catalog ..&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;After some reading, I query the service &lt;a href=&quot;https://www.consul.io/api/catalog.html#list-services&quot;&gt;catalog API&lt;/a&gt; to get some more meta information:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;curl -sX PUT http://localhost:8500/v1/catalog/service/:service_name
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;The result of this query looks like that:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ curl -sX PUT http://localhost:8500/v1/catalog/service/vault | jq
[
  {
    &quot;ID&quot;: &quot;&amp;lt;uuid&amp;gt;&quot;,
    &quot;Node&quot;: &quot;kernel-terra-vault-0&quot;,
    &quot;Address&quot;: &quot;10.5.1.200&quot;,
    &quot;TaggedAddresses&quot;: {
      &quot;lan&quot;: &quot;10.5.1.200&quot;,
      &quot;wan&quot;: &quot;10.5.1.200&quot;
    },
    &quot;NodeMeta&quot;: {},
    &quot;ServiceID&quot;: &quot;vault:10.5.1.200:8200&quot;,
    &quot;ServiceName&quot;: &quot;vault&quot;,
    &quot;ServiceTags&quot;: [
      &quot;active&quot;
    ],
    &quot;ServiceAddress&quot;: &quot;10.5.1.200&quot;,
    &quot;ServicePort&quot;: 8200,
    &quot;ServiceEnableTagOverride&quot;: false,
    &quot;CreateIndex&quot;: &amp;lt;some index&amp;gt;,
    &quot;ModifyIndex&quot;: &amp;lt;some index&amp;gt;
  },
  {
    &quot;ID&quot;: &quot;&amp;lt;uuid&amp;gt;&quot;,
    &quot;Node&quot;: &quot;kernel-terra-vault-1&quot;,
    &quot;Address&quot;: &quot;10.5.1.201&quot;,
    &quot;TaggedAddresses&quot;: {
      &quot;lan&quot;: &quot;10.5.1.201&quot;,
      &quot;wan&quot;: &quot;10.5.1.201&quot;
    },
    &quot;NodeMeta&quot;: {},
    &quot;ServiceID&quot;: &quot;vault:10.5.1.201:8200&quot;,
    &quot;ServiceName&quot;: &quot;vault&quot;,
    &quot;ServiceTags&quot;: [
      &quot;standby&quot;
    ],
    &quot;ServiceAddress&quot;: &quot;10.5.1.201&quot;,
    &quot;ServicePort&quot;: 8200,
    &quot;ServiceEnableTagOverride&quot;: false,
    &quot;CreateIndex&quot;: &amp;lt;some index&amp;gt;,
    &quot;ModifyIndex&quot;: &amp;lt;some index&amp;gt;
  },
  {
    &quot;ID&quot;: &quot;&amp;lt;uuid&amp;gt;&quot;,
    &quot;Node&quot;: &quot;kernel-terra-vault-1&quot;,
    &quot;Address&quot;: &quot;10.5.1.100&quot;,
    &quot;TaggedAddresses&quot;: {
      &quot;lan&quot;: &quot;10.5.1.100&quot;,
      &quot;wan&quot;: &quot;10.5.1.100&quot;
    },
    &quot;NodeMeta&quot;: {},
    &quot;ServiceID&quot;: &quot;vault:10.5.1.100:8200&quot;,
    &quot;ServiceName&quot;: &quot;vault&quot;,
    &quot;ServiceTags&quot;: [
      &quot;standby&quot;
    ],
    &quot;ServiceAddress&quot;: &quot;10.5.1.100&quot;,
    &quot;ServicePort&quot;: 8200,
    &quot;ServiceEnableTagOverride&quot;: false,
    &quot;CreateIndex&quot;: &amp;lt;some index&amp;gt;,
    &quot;ModifyIndex&quot;: &amp;lt;some index&amp;gt;
  }
]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p class=&quot;text-justify&quot;&gt;Very interesting! It looks like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;:service_id&lt;/code&gt; is actually a combination of the service name, the node’s ip and the service port! 
This means that for one service across the whole cluster every offering node has a unique &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;:service_id&lt;/code&gt; for that service.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;In my case, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10.5.1.100&lt;/code&gt; is the consul server node on which I want to deregister vault. I run:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ curl -sX PUT http://localhost:8500/v1/agent/service/deregister/vault:10.5.1.100:8200
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;It worked! The faulty vault service got successfully deregistered on server node &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;10.5.1.100&lt;/code&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Lesson learned: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;:service_id != :service_name&lt;/code&gt;&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;Note: You should do the mentioned queries against a consul agent with the necessary privileges in case you activated the &lt;a href=&quot;https://www.consul.io/docs/guides/acl.html&quot;&gt;consul ACL&lt;/a&gt;. In any case it should work if you do the query against the agent on which the service is running that you want to deregister, as usually that node must have permissions to register/deregister the service in the first place.&lt;/p&gt;
&lt;/div&gt;

</description>
        <pubDate>Sat, 09 Sep 2017 09:21:22 +0000</pubDate>
        <link>http://fishi0x01.devtail.com/weblog/2017/09/09/consul-service-id-hunt/</link>
        <guid isPermaLink="true">http://fishi0x01.devtail.com/weblog/2017/09/09/consul-service-id-hunt/</guid>
        
        
        <category>consul</category>
        
      </item>
    
      <item>
        <title>A Docker Build Pipeline as Code with Jenkins</title>
        <description>&lt;p class=&quot;text-justify&quot;&gt;Since quite some time now we are no longer satisfied with only having our App Layer as code in repositories, but we also want every other component of our system codified. 
After &lt;a href=&quot;https://en.wikipedia.org/wiki/Infrastructure_as_Code&quot;&gt;Infrastructure as Code&lt;/a&gt; (e.g., &lt;a href=&quot;https://www.terraform.io/&quot;&gt;Terraform&lt;/a&gt;) and Configuration as Code a.k.a. &lt;a href=&quot;https://en.wikipedia.org/wiki/Continuous_configuration_automation&quot;&gt;Continuous Configuration Automation&lt;/a&gt; (e.g., &lt;a href=&quot;https://www.ansible.com/&quot;&gt;Ansible&lt;/a&gt; and &lt;a href=&quot;https://saltstack.com/&quot;&gt;SaltStack&lt;/a&gt;) approaches, we also 
want our automation itself codified: Pipeline as Code!&lt;!--more--&gt;
Some of the big advantages of managing system components in code are:&lt;/p&gt;

&lt;ul class=&quot;text-justify&quot;&gt;
  &lt;li&gt;It is easier for teams to work on the same complex components if they are managed in code repositories&lt;/li&gt;
  &lt;li&gt;Each aspect of your system can be versionized&lt;/li&gt;
  &lt;li&gt;Codified components can be easier used for further automation&lt;/li&gt;
&lt;/ul&gt;

&lt;p class=&quot;text-justify&quot;&gt;External CI providers such as &lt;a href=&quot;https://travis-ci.org/&quot;&gt;Travis&lt;/a&gt; or &lt;a href=&quot;https://circleci.com/&quot;&gt;Circle CI&lt;/a&gt; made the Pipeline as Code principle very popular - especially amongst OSS Projects.
Nevertheless, external CI providers may not support all of your Pipeline needs and even more important: A Pipeline may contain information you do not want to share with external providers. 
Personally, I pretty much trust the guys from Travis and for OSS projects they are way to go (not saying no to free checks and badges!), but if they get compromised the Pipeline data is exposed. 
Beginning with version 2, &lt;a href=&quot;https://jenkins.io/solutions/pipeline/&quot;&gt;Jenkins finally supports the Pipeline as Code approach&lt;/a&gt; with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Jenkinsfile&lt;/code&gt;, which brings our Pipeline back into our own hands. 
In this post I want to outline how to build a simple codified Pipeline in Jenkins to containerize a Java project with Docker. 
I will solely focus on the Pipeline code. No Maven/Java code examples will be given here.&lt;/p&gt;

&lt;h2 id=&quot;setup-assumptions&quot;&gt;Setup Assumptions&lt;/h2&gt;

&lt;p&gt;I am assuming that you have a Maven Project which builds &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;target/project.war&lt;/code&gt; via &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mvn clean package -U&lt;/code&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;I also assume that you have a running Jenkins 2.x with access to a Docker Daemon (locally or remote). 
In case you are running Jenkins inside a container, you have to give it access to a Docker Daemon socket, either by sharing 
the docker hosts socket with the container or by using a remote server.&lt;/p&gt;
&lt;!-- TODO: post about this issue --&gt;

&lt;p class=&quot;text-justify&quot;&gt;Jenkins must have read access to your code repository (which can easily be established using &lt;a href=&quot;https://developer.github.com/guides/managing-deploy-keys/&quot;&gt;deploy keys&lt;/a&gt;).&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Jenkins must have Maven configured as a global tool referenced as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;M3&lt;/code&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Further, we need the following Jenkins plugins installed:&lt;/p&gt;

&lt;ul class=&quot;text-justify&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;https://wiki.jenkins-ci.org/display/JENKINS/Slack+Plugin&quot;&gt;Slack Notification&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://wiki.jenkins-ci.org/display/JENKINS/Docker+Pipeline+Plugin&quot;&gt;Docker Pipeline&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;the-jenkins-docker-pipeline&quot;&gt;The Jenkins Docker Pipeline&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;For our Java project, let us build a pipeline which handles the following steps:&lt;/p&gt;

&lt;ul class=&quot;text-justify&quot;&gt;
  &lt;li&gt;Checkout a branch from a SCM&lt;/li&gt;
  &lt;li&gt;Set a branch SNAPSHOT version inside the pom file&lt;/li&gt;
  &lt;li&gt;Build a .war package for the checked out branch&lt;/li&gt;
  &lt;li&gt;Build a docker image containing this .war package&lt;/li&gt;
  &lt;li&gt;Send notifications to a Slack channel&lt;/li&gt;
&lt;/ul&gt;

&lt;p class=&quot;text-justify&quot;&gt;To get started, we first create a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;build.groovy&lt;/code&gt; file inside our Java code repository, ideally on a new branch, which we call &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jenkins&lt;/code&gt;.&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;&lt;strong&gt;NOTE:&lt;/strong&gt; Some Plugins, such as the &lt;a href=&quot;https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Multibranch+Plugin&quot;&gt;Multibranch Pipeline Plugin&lt;/a&gt; 
require that the pipeline code is in a single file called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Jenkinsfile&lt;/code&gt; in the repositorie’s root.&lt;/p&gt;
&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;The reason why we put the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;build.groovy&lt;/code&gt; on a separate branch is to decouple the app code from the pipeline code. 
Imagine you want to build a feature branch, but something in your pipeline changed. 
You would need to push a new commit with that pipeline change on the feature branch. 
This is especially bad, if you want to build a specific commit, e.g., a tag, since that would require you to re-tag. 
On the other hand this approach adds more complexity to your project, as an extra branch for pipelines may not be 
as intuitive as keeping the pipeline defintions with the rest of your code in the same branch. 
A better approach would be to use the &lt;a href=&quot;https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Multibranch+Plugin&quot;&gt;Multibranch Pipeline Plugin&lt;/a&gt;, also because it 
is a requirement to get the most out of the new Jenkins UI &lt;a href=&quot;https://wiki.jenkins-ci.org/display/JENKINS/Blue+Ocean+Plugin&quot;&gt;Blue Ocean&lt;/a&gt;.
However, in this post we are satisfied with a separate branch. 
The repositorie’s dir structure may now look something like this:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;project/
├── .jenkins
│   └── build.groovy
├── pom.xml
└── src
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;Initially, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;build.groovy&lt;/code&gt; script may contain the following for testing purposes:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/9c8d39d7a79cbe454f87c4745897d561.js?file=initial-test-build.groovy&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;Now, we create a Jenkins Pipeline job, which checks out the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jenkins&lt;/code&gt; branch of our project and looks 
for the pipeline file &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.jenkins/build.groovy&lt;/code&gt;. The configuration may look something like this:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/content-images/jenkins-pipeline-job.png&quot; alt=&quot;Jenkins Pipeline Job&quot; style=&quot;display: block; margin-left: auto; margin-right: auto;&quot; /&gt;&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;When we run this job, it should print &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;The pipeline started&lt;/code&gt; in the job’s console output.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;In a next step, we want to build a SNAPSHOT package of a branch. 
The branch is given as an input variable named &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BRANCH_NAME&lt;/code&gt;. 
It can be given to the job as a simple String input parameter or by using the &lt;a href=&quot;https://wiki.jenkins-ci.org/display/JENKINS/Git+Parameter+Plugin&quot;&gt;Git Parameter Plugin&lt;/a&gt; and 
is referenced inside the pipeline script as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;env.BRANCH_NAME&lt;/code&gt;. 
We want our branch SNAPSHOTs to have the following version naming pattern: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;version&amp;gt;-&amp;lt;branchName&amp;gt;-SNAPSHOT&lt;/code&gt;, where &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;version&amp;gt;&lt;/code&gt; is taken from the checked out &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pom.xml&lt;/code&gt; 
and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;branchName&lt;/code&gt; is given as an input parameter &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;env.BRANCH_NAME&lt;/code&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Let’s extend our pipeline script to checkout and build the specified branch:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/9c8d39d7a79cbe454f87c4745897d561.js?file=java-build.groovy&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;This pipeline checks out the specified branch, determines and sets the proper branch snapshot version inside the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pom.xml&lt;/code&gt; 
and finally builds the .war file. 
Next, we move on to packaging our .war inside a Tomcat docker image. 
We create a docker build context in our project’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jenkins&lt;/code&gt; branch, which will give us the following directory structure:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;project/
├── .docker
│   └── build
│       ├── docker-entrypoint.sh
│       └── Dockerfile
├── .jenkins
│   └── build.groovy
├── pom.xml
└── src
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Dockerfile&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;docker-entrypoint.sh&lt;/code&gt; may contain the following:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/9c8d39d7a79cbe454f87c4745897d561.js?file=Dockerfile&quot;&gt; &lt;/script&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;&lt;strong&gt;IMPORTANT:&lt;/strong&gt; By default the resulting container will run as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;root&lt;/code&gt;. This should be avoided if possible, since the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;root&lt;/code&gt; 
user inside the container has the same uuid as the host’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;root&lt;/code&gt; user, which is potentially dangerous in case the container gets compromised.&lt;/p&gt;
&lt;/div&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/9c8d39d7a79cbe454f87c4745897d561.js?file=docker-entrypoint.sh&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;docker-entrypoint.sh&lt;/code&gt; allows our container to be configured via environment variables, making it more flexible to run in different environments. 
Further, we adjust our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;build.groovy&lt;/code&gt; script to build and push a functional docker image:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/9c8d39d7a79cbe454f87c4745897d561.js?file=docker-build.groovy&quot;&gt; &lt;/script&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;Note, that we also adjusted the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Checkout&lt;/code&gt; stage, to copy the docker build context to another location before we switch branches (the build context might not be available on the new branch).
Also, this pipeline does not contain important aspects such as testing or uploading of the .war file to a java package manager like &lt;a href=&quot;https://www.jfrog.com/open-source/&quot;&gt;Artifactory&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;withDockerServer&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;withDockerRegistry&lt;/code&gt; are built-in wrappers by Jenkins’ &lt;a href=&quot;https://wiki.jenkins-ci.org/display/JENKINS/Docker+Plugin&quot;&gt;docker-plugin&lt;/a&gt; 
and allow us to use a remote host to build the docker image (very handy when running the Jenkins master inside a container itself) and to 
define a custom private docker registry (most likely you do not store your companie’s docker images on dockerhub).&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Finally, let us add some visibility to our build by sending the build status to a slack channel. 
We slightly modify our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;build.groovy&lt;/code&gt;:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/9c8d39d7a79cbe454f87c4745897d561.js?file=slack-build.groovy&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;That’s it! We now have a Pipeline which handles our Docker image builds for specific branches and sends the results to a Slack channel. 
In a future post I will show how to share Groovy libraries between Jenkins jobs to apply the &lt;a href=&quot;https://en.wikipedia.org/wiki/Don&apos;t_repeat_yourself&quot;&gt;DRY principle&lt;/a&gt; to your Pipeline code.&lt;/p&gt;

</description>
        <pubDate>Mon, 21 Nov 2016 19:25:09 +0000</pubDate>
        <link>http://fishi0x01.devtail.com/weblog/2016/11/20/docker-build-pipeline-as-code-jenkins/</link>
        <guid isPermaLink="true">http://fishi0x01.devtail.com/weblog/2016/11/20/docker-build-pipeline-as-code-jenkins/</guid>
        
        
        <category>jenkins</category>
        
        <category>docker</category>
        
        <category>build-pipeline</category>
        
        <category>groovy</category>
        
      </item>
    
      <item>
        <title>Ansible role structuring</title>
        <description>&lt;p class=&quot;text-justify&quot;&gt;In this short post I want to talk about structuring Ansible roles in a way that OS specific tasks and variables are cleanly separated from the other common logic of the role.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;My main sources of inspiration for role structuring are &lt;a href=&quot;https://galaxy.ansible.com/&quot;&gt;Ansible Galaxy&lt;/a&gt; and the &lt;a href=&quot;https://github.com/debops&quot;&gt;DebObs repository&lt;/a&gt; and I would like to share my findings here.&lt;!--more--&gt;&lt;/p&gt;

&lt;h2 id=&quot;a-simple-ssh-role&quot;&gt;A simple ssh role&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Let’s first quickly discuss the directory structure of an Ansible role. 
In general, we have a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tasks&lt;/code&gt; directory, which contains each task that has to be executed for that role. 
Further, we got the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;handlers&lt;/code&gt; directory, which contains service handlers which can be called from any task. 
We also have a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vars&lt;/code&gt; directory, which as the name already can contain variables. 
Jinja2 templates and static files are being stored inside the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;templates&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;files&lt;/code&gt; directory respectively. 
Another common directory is the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;defaults&lt;/code&gt; directory, which could be used for OS independant variables.&lt;/p&gt;

&lt;pre&gt;
ssh
├── defaults
├── files
├── handlers
├── tasks
├── templates
└── vars
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;In each directory, except &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;files&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;templates&lt;/code&gt;, the file &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;main.yml&lt;/code&gt; gets included automatically when you use the role.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Now, to write our ssh role for Ubuntu 14.04 we would need a template for the sshd configuration.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;templates/sshd_config.j2&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=roles-ssh-templates-sshd_config.j2&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;Next, we need a handler for the sshd service.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;handlers/main.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=roles-ssh-handlers-main.yml&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;Further, we need tasks which ensure that sshd is installed and the ssh config template gets rendered and deployed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;tasks/main.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=roles-ssh-tasks-main.yml&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;Finally, we could define some common variables.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;defaults/main.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=roles-ssh-defaults-main.yml&quot;&gt; &lt;/script&gt;

&lt;h2 id=&quot;a-more-mature-role-structure&quot;&gt;A more mature role structure&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;While the above approach does work for Ubuntu 14.04, we still would like to easily extend our role for any other OS too. 
One easy way to do so, is by separating OS specific tasks and variables in different OS dedicated files. 
Ansible helps us to automatically identify the currently used distribution with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{{ ansible_distribution }}&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{{ ansible_distribution_version }}&lt;/code&gt;, so we just have to name the OS dedicated yml files accordingly and include them in our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;main.yml&lt;/code&gt; files.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;For our ssh role, the dir tree would then look something like that:&lt;/p&gt;

&lt;pre&gt;
ssh
├── defaults
│   └── main.yml
├── handlers
│   ├── main.yml
│   └── Ubuntu14.04.yml
├── tasks
│   ├── main.yml
│   └── Ubuntu14.04.yml
├── templates
│   └── Ubuntu14_04.sshd_config.j2
└── vars
    └── Ubuntu14.04.yml
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;Here are the gists of the files.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;defaults/main.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/6a1a139e821af26e8d2bbfb71a7b37c2.js?file=defaults-main.yml&quot;&gt; &lt;/script&gt;

&lt;p&gt;&lt;strong&gt;handlers/main.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/6a1a139e821af26e8d2bbfb71a7b37c2.js?file=ssh-handlers-main.yml&quot;&gt; &lt;/script&gt;

&lt;p&gt;&lt;strong&gt;handlers/Ubuntu14.04.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/6a1a139e821af26e8d2bbfb71a7b37c2.js?file=ssh-handlers-ubuntu.yml&quot;&gt; &lt;/script&gt;

&lt;p&gt;&lt;strong&gt;tasks/main.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/6a1a139e821af26e8d2bbfb71a7b37c2.js?file=ssh-tasks-main.yml&quot;&gt; &lt;/script&gt;

&lt;p&gt;&lt;strong&gt;tasks/Ubuntu14.04.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/6a1a139e821af26e8d2bbfb71a7b37c2.js?file=ssh-tasks-ubuntu.yml&quot;&gt; &lt;/script&gt;

&lt;p&gt;&lt;strong&gt;vars/Ubuntu14.04.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/6a1a139e821af26e8d2bbfb71a7b37c2.js?file=vars-ubuntu.yml&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;In that way we separated OS specific variables in dedicated files inside the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vars&lt;/code&gt; directory. 
Also OS specific tasks and handlers can now easily be separated. 
Ansible detects the OS it operates on and includes the dedicated files.&lt;/p&gt;

</description>
        <pubDate>Thu, 02 Jun 2016 15:47:09 +0000</pubDate>
        <link>http://fishi0x01.devtail.com/weblog/2016/06/02/ansible-role-structuring/</link>
        <guid isPermaLink="true">http://fishi0x01.devtail.com/weblog/2016/06/02/ansible-role-structuring/</guid>
        
        
        <category>ansible</category>
        
      </item>
    
      <item>
        <title>Testing ansible playbooks with ansible-vault encrypted data using Travis CI</title>
        <description>&lt;p class=&quot;text-justify&quot;&gt;In this post I want to talk about using &lt;a href=&quot;http://docs.ansible.com/ansible/playbooks_vault.html&quot;&gt;ansible-vault&lt;/a&gt; to encrypt secret variables and templates in your ansible roles. 
Further, I want to have a look at how to test those playbooks and encrypted files using &lt;a href=&quot;https://travis-ci.org/&quot;&gt;Travis CI&lt;/a&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;The combination of ansible-vault and Travis CI seems a little odd on first sight and I must admit I’ve had trouble finding a proper way of handling private data in a public repository with an external and also public CI environment. 
Here is some little background information why I still chose such an approach:&lt;!--more--&gt;
My use case is an &lt;a href=&quot;https://github.com/himate&quot;&gt;open source project&lt;/a&gt; which uses ansible provisioning for its infrastructure. 
One sweet thing about ansible is that it is highly supported by tools such as &lt;a href=&quot;https://www.packer.io/&quot;&gt;Packer&lt;/a&gt; and &lt;a href=&quot;https://www.vagrantup.com/&quot;&gt;Vagrant&lt;/a&gt; (&lt;a href=&quot;https://www.hashicorp.com/&quot;&gt;HashiCorp&lt;/a&gt; in general does some really awesome stuff - I am also already curious to play around with &lt;a href=&quot;https://www.ottoproject.io/&quot;&gt;Otto&lt;/a&gt; and &lt;a href=&quot;https://www.vaultproject.io/&quot;&gt;Vault&lt;/a&gt; (not to be confused with ansible-vault)). 
I use Vagrant locally to develop my ansible roles and Packer can be used to create images (also &lt;a href=&quot;https://www.docker.com/&quot;&gt;docker&lt;/a&gt; containers are possible) with these roles/playbooks which basically enables me to port my ansible described architecture to any kind of machine image. 
I find it tempting to also share infrastructure code, such as ansible scripts publicly, without risking security issues, but of course parts of the infrastructure such as keys, passwords etc. have to be kept secret. 
Further, when developing open source I can use services such as Travis CI to test my playbooks and roles for free, so I could test the whole setup instead of just single role rollouts. 
In the end of this post I will talk a little more about some security concerns. 
I think keeping up such an open approach in a secure way requires more maintenance on my side, but it is also an interesting challenge!&lt;/p&gt;

&lt;h2 id=&quot;ansible---a-simple-example-playbook&quot;&gt;Ansible - A simple example playbook&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Lets first create a simple ssh role and playbook. 
In the next sections we will then step by step encrypt sensitive parts of that role. 
First, we create a template for the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sshd_config&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;roles/ssh/templates/sshd_config.j2&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=roles-ssh-templates-sshd_config.j2&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;This &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sshd_config&lt;/code&gt; handles access permissions based on the user groups. 
The group list &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;all_groups&lt;/code&gt;, which contains all groups with ssh permissions must be visible for this template to render. 
Next, we define the task for the role. 
Basically all we need is to place the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sshd_config&lt;/code&gt; file and restart the ssh daemon.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;roles/ssh/tasks/main.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=roles-ssh-tasks-main.yml&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;Now we need to define our default variables.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;roles/ssh/defaults/main.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=roles-ssh-defaults-main.yml&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;Please note, that the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sshd_groups&lt;/code&gt; list could also be defined in a users/groups role, but to keep it simple we just define it for now as a defaults variable in our ssh role. 
We also need a service handler to restart our service.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;roles/ssh/handlers/main.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=roles-ssh-handlers-main.yml&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;Next, we need a playbook which uses our role.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;app.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=app.yml&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;This playbook rolls out the ssh role on all hosts in our inventory with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app&lt;/code&gt; tag. 
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;no_log&lt;/code&gt; is set to avoid the logging of secret data in Travis later. 
Of course, while actively working on a playbook/role it might be easier for debugging to turn the logging on again by setting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;no_log: no&lt;/code&gt;, so inside the Travis build we just have to hand over an extra argument to disable the logging &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;--extra-vars=&apos;{\&quot;disable_log\&quot;: \&quot;yes\&quot;}&apos;&lt;/code&gt;. 
Finally, we need an inventory file for development.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;inventories/dev&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=inventories-dev&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;Note, that the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app&lt;/code&gt; host needs to be resolvable in order for this to work. 
You could add it to your &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/etc/hosts&lt;/code&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;We could now run our playbook via:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;

ansible-playbook -i inventories/dev app.yml
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;We now have a simple and fully functional playbook. 
In the next sections I want to encrypt the secrets in our playbook and run tests via Travis CI.&lt;/p&gt;

&lt;h2 id=&quot;encrypting-secrets-with-ansible-vault&quot;&gt;Encrypting secrets with ansible-vault&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Now we discuss how we can encrypt secrets that should not be shared with everyone inside your company. 
First, we will have a look at how to encrypt and use secret variables. Second, we will look at secret config files / templates.&lt;/p&gt;

&lt;h3 id=&quot;secret-variables&quot;&gt;Secret Variables&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;In Ansible we can use a feature called &lt;a href=&quot;http://docs.ansible.com/ansible/playbooks_vault.html&quot;&gt;ansible-vault&lt;/a&gt; in order to encrypt our files which contain secrets. 
Simply use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ansible-vault encrypt &amp;lt;file&amp;gt;&lt;/code&gt; in order to encrypt an existing file. 
You can also edit encrypted files (without decrypting them first on the disk) with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ansible-vault edit &amp;lt;file&amp;gt;&lt;/code&gt; or create a new encrypted file via &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ansible-vault create &amp;lt;file&amp;gt;&lt;/code&gt;. 
Please consult the &lt;a href=&quot;http://docs.ansible.com/ansible/playbooks_vault.html&quot;&gt;documentation&lt;/a&gt; for more commands of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ansible-vault&lt;/code&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;By storing the vault password in a file we can use our playbooks without decrypting the encrypted files directly on the disk. 
As an example we could use the following command to rollout a playbook with vault encrypted files:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;

ansible-playbook -i inventories/travis my-playbook.yml --vault-password-file vault_pass_file
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;Ansible will then decrypt the files in memory and rollout the playbook.&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;Remember to add the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vault_pass_file&lt;/code&gt; to your &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.gitignore&lt;/code&gt;, so you do not add the password to your repository by accident.&lt;/p&gt;
&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;For our playbook example from the previous section, we could encrypt our default variables, to keep our port and group access settings a secret. 
First, we generate a complex vault password and store it in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vault_pass_file&lt;/code&gt;. 
Then, we run:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;

ANSIBLE_VAULT_PASSWORD_FILE=vault_pass_file ansible-vault encrypt roles/ssh/defaults/main.yml
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;We could then rollout the playbook via:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;

ansible-playbook -i inventories/dev app.yml --vault-password-file vault_pass_file
&lt;/pre&gt;

&lt;h3 id=&quot;secret-templates&quot;&gt;Secret Templates&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;In the first place &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ansible-vault&lt;/code&gt; is designed to encrypt files containing secret variables, such as files in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;group_vars&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;host_vars&lt;/code&gt; directories, but theoretically we can also use it to encrypt templates. 
If I want to keep config files such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sshd_config&lt;/code&gt; or nginx config files secret, then I can use ansible-vault to encrypt their templates. 
The problem with encrypting templates is that ansible assumes that templates or files which are copied to the server are already unencrypted. 
Thus, we cannot use on the fly in memory decryption by simply specifying the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;--vault-password-file&lt;/code&gt; flag, but we need to decrypt the templates/files on disk before we rollout playbooks. 
There is a &lt;a href=&quot;https://github.com/ansible/ansible/issues/6596&quot;&gt;discussion&lt;/a&gt; on github about enabling this feature and currently there is &lt;a href=&quot;https://github.com/ansible/ansible/pull/8110&quot;&gt;some work&lt;/a&gt; done on the file lookup feature to allow encrypted templates/files.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Lets rename our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sshd_config.j2&lt;/code&gt; template to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sshd_config.j2.enc&lt;/code&gt; and encrypt it by simply running:&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;

ANSIBLE_VAULT_PASSWORD_FILE=vault_pass_file ansible-vault encrypt roles/ssh/templates/sshd_config.j2.enc
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;We now need to make a small adjustment to our ssh role’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;main.yml&lt;/code&gt;, so it first locally decrypts the template and after the rollout removes the decrypted template again.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Modified roles/ssh/tasks/main.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=roles-ssh-tasks-main-decrypt.yml&quot;&gt; &lt;/script&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;Note, that I set &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;changed_when: False&lt;/code&gt; for decryption and removal, since without it each run would result in changes, which would make idempotency tests very difficult. 
Also, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;local_action&lt;/code&gt; has problems to source the python virtualenv inside Travis, which is why I handle the decryption inside Travis with a separate script. 
This does not affect non-Travis rollouts.&lt;/p&gt;
&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;In case we are not dealing with templates, but with static encrypted files instead, we could use the Ansible &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lookup&lt;/code&gt; feature together with the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;content&lt;/code&gt; setting of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;copy&lt;/code&gt; module:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
content={{ lookup(&apos;pipe&apos;, &apos;ansible-vault --vault-password-file vault_pass_file view secret.file&apos;) }}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;travis-ci---testing-my-playbooks&quot;&gt;Travis CI - Testing my playbooks&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;We now want to test our playbooks with &lt;a href=&quot;https://travis-ci.org/&quot;&gt;Travis CI&lt;/a&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;In general this is very easy to setup, but when using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ansible-vault&lt;/code&gt; encrypted files we need to do some extra steps in order for Travis to know the vault password.&lt;/p&gt;

&lt;h3 id=&quot;simple-tests-without-encryption&quot;&gt;Simple tests without encryption&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;First, we create simple ansible tests assuming our files are all unencrypted. 
We need a Travis CI account (for open source projects you can use Travis for free!). 
Travis uses a file called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.travis.yml&lt;/code&gt; in the top directory of your project to read the test configurations. 
You can use this file to setup and run your tests inside the Travis infrastructure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;.travis.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=decrypted.travis.yml&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;This configuration initially installs ansible inside the Travis VM. 
It also sets &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app&lt;/code&gt; in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/etc/hosts&lt;/code&gt; to point to localhost. 
Next, we run 3 tests in the script section. 
The first test is a simple syntax check to catch the most obvious errors. 
Next, we rollout the playbook against the local VM. 
Finally, we make an idempotence test by rolling out the same playbook against localhost again. 
In order to succeed this test, there should not be any changes.&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;Currently we only have one playbook to test, but we can simply test multiple playbooks in parallel by adding them to the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;env.matrix&lt;/code&gt; section. 
For instance if we had a playbook &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;db.yml&lt;/code&gt;, we could also test it in parallel by simply adding it to the test matrix:&lt;/p&gt;

  &lt;pre&gt;
env:
  global:
    - ANSIBLE_VERSION=2.0.1.0
  matrix:
    - PLAYBOOK=app.yml
    - PLAYBOOK=db.yml
&lt;/pre&gt;
&lt;/div&gt;

&lt;h3 id=&quot;tests-with-encrypted-files&quot;&gt;Tests with encrypted files&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;We also want to test our playbooks when they reference encrypted variables and in order for this to work we need to give Travis knowledge about how to decrypt them. 
For each project Travis generates a public / private keypair, which can be used to share secrets. 
We can then use the &lt;a href=&quot;https://github.com/travis-ci/travis.rb&quot;&gt;Travis CLI&lt;/a&gt; to encrypt values which can later be decrypted by the private key inside the Travis infrastructure for your project. 
Here is the official documentation about &lt;a href=&quot;https://docs.travis-ci.com/user/encrypting-files/&quot;&gt;file encryption in Travis&lt;/a&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;In our case one way to approach this problem is by encrypting our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vault_pass_file&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vault_pass_file.enc&lt;/code&gt; with a complex password via OpenSSL.&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;

openssl aes-256-cbc -k &quot;&amp;lt;my-very-strong-password&amp;gt;&quot; -in vault_pass_file -out vault_pass_file.enc
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;We could then add the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vault_pass_file.enc&lt;/code&gt; to our repository and use Travis CLI to give Travis knowledge about the password to be able to decrypt the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vault_pass_file.enc&lt;/code&gt;. 
To share the password with travis, we first need to authenticate with Travis CLI.&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;

travis login
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;Next, we need to define an encrypted environment variable (in our case we name it &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vault_file_pass&lt;/code&gt;) which stores the password.&lt;/p&gt;

&lt;pre style=&quot;background: black; color: #00FF00;&quot;&gt;

travis encrypt vault_file_pass=&amp;lt;my-very-strong-password&amp;gt; --add
&lt;/pre&gt;

&lt;p class=&quot;text-justify&quot;&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;--add&lt;/code&gt; flag adds the encrypted data to your &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;env&lt;/code&gt; map inside the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.travis.yml&lt;/code&gt; file.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Finally, we need to tell Travis to decrypt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vault_pass_file.enc&lt;/code&gt; in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;before_install&lt;/code&gt; step and decrypt the template files for the tests. 
Your &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.travis.yml&lt;/code&gt; file should now look something like that.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;.travis.yml&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=var_encrypted.travis.yml&quot;&gt; &lt;/script&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p class=&quot;text-justify&quot;&gt;Note, that after running the tests I run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.travis/sensitive_data.sh clean&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;shred vault_pass_file&lt;/code&gt; in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;after_script&lt;/code&gt; section to remove the decrypted flles and the cleartext vault password from the Travis VM.&lt;/p&gt;
&lt;/div&gt;

&lt;p class=&quot;text-justify&quot;&gt;As mentioned above, I had trouble using &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;local_action&lt;/code&gt; within the Travis environment, since it does not properly source the python virtual environment and thus cannot find the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ansible-vault&lt;/code&gt; command. 
I am still investigating this, but in the meanwhile as a workaround I wrote a script that Travis can use to decrypt the templates before running (and also clean them up after the build is done).&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;Here is an example of what the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.travis/sensitive_data.sh&lt;/code&gt; could look like:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;.travis/sensitive_data.sh&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/4d613f4fb0034b7197a92cd36bd34801.js?file=.travis_sensitive_data.sh&quot;&gt; &lt;/script&gt;

&lt;h3 id=&quot;some-security-concerns&quot;&gt;Some security concerns&lt;/h3&gt;

&lt;p class=&quot;text-justify&quot;&gt;While testing with Travis CI is quite comfortable, an obvious issue is that Travis needs to be able to decrypt your secrets. 
Also, you create VMs/Containers inside the Travis infrastructure which contain your decrypted setups. 
This means, that if Travis gets compromised so are your secrets. 
To work around that issue you should consider using fake data in your tests for the most important secrets such as private keys (go snakeoil!!!). 
That way the provisioned VMs/Containers do not hold any critical security relevant keys. 
What makes this approach difficult is that ansible-vault only allows one vault password for all the files. 
Thus, we should at least store real private keys in a different directory which is not part of the repository or encrypt them using another password (which means we would need to decrypt them on disk before using them again, since ansible will use the same provided password to decrypt all the files). 
Your templates and less important secret variables are still visible to Travis, but at least your private keys and other very important secrets are kept private. 
Another issue is if your tests require valid SSL certificates in order to run (think end-to-end testing). 
In that case you might need to apply some workarounds in your test scripts to allow insecure certificates. 
Of course this adds more maintenance work on your part, but the privacy of your private keys should be worth the effort.&lt;/p&gt;

</description>
        <pubDate>Sat, 02 Apr 2016 16:03:23 +0000</pubDate>
        <link>http://fishi0x01.devtail.com/weblog/2016/04/02/testing-ansible-ansible-vault-travis-ci/</link>
        <guid isPermaLink="true">http://fishi0x01.devtail.com/weblog/2016/04/02/testing-ansible-ansible-vault-travis-ci/</guid>
        
        
        <category>ansible</category>
        
        <category>ci</category>
        
      </item>
    
      <item>
        <title>Computing Large Binomial Coefficients Modulo Prime / Non-Prime</title>
        <description>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.6/MathJax.js?config=TeX-AMS_HTML&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/x-mathjax-config&quot;&gt;MathJax.Hub.Config({tex2jax: {inlineMath: [[&apos;\\(&apos;,&apos;\\)&apos;]]}});&lt;/script&gt;

&lt;p&gt;Not rarely, in combinatoric problems it comes down to calculating the &lt;a href=&quot;https://en.wikipedia.org/wiki/Binomial_coefficient&quot;&gt;binomial coefficient&lt;/a&gt; \(n \choose k\) for very large \(n\) and/or \(k\) modulo a number \(m\). 
In general, the binomial coefficient can be formulated with &lt;a href=&quot;https://en.wikipedia.org/wiki/Factorial&quot;&gt;factorials&lt;/a&gt; as \({n \choose k} = \frac{n!}{k!(n-k)!}, 0 \leq k \leq n\). 
The problem here is that factorials grow extremely fast which makes this formula computationally unsuitable because of quick overflows. 
For that reason, many problems in that category require the calculation of \({n \choose k} \mod m\). 
In this post I want to discuss ways to calculate the binomial coefficients for cases in which \(m\) is prime and when \(m\) is non-prime.&lt;!--more--&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-first-simple-approaches-for-any-m&quot;&gt;1. First simple approaches for any \(m\)&lt;/h2&gt;

&lt;p&gt;The good news is that there are easy ways to compute the binomial coefficient for any modulo \(m\) - the bad news is that they are not feasible for very large numbers. 
However, we will see later that we can break down very large numbers into sub-problems of much smaller numbers, in which case we can re-use techniques that we discuss now.&lt;/p&gt;

&lt;h3 id=&quot;using-pascals-triangle&quot;&gt;Using Pascal’s Triangle&lt;/h3&gt;
&lt;p&gt;The easiest (but also most limited) way to tackle this problem is to use a bottom-up dynamic programming approach by pre-computing &lt;a href=&quot;https://en.wikipedia.org/?title=Pascal%27s_triangle&quot;&gt;Pascal’s Triangle&lt;/a&gt;. 
Pascal’s Triangle can be seen as a lookup table, where \(n \choose k\) is the value at the \(n\)th row in the \(k\)th column. 
Pre-computing Pascal’s Triangle is very easy, since the current value is simply the sum of two neighboring cells from the previous row. 
We know that \((a+b) \mod m =\)\( (a \mod m) +\)\( (b \mod m) \mod m\), thus we can calculate each cell of Pascal’s Triangle with the modulo to avoid overflows.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code: Computing Pascal’s Triangle, for any \(m\)&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/46ebb1d310df5f9b5d8c.js?file=pascal_triangle.py&quot;&gt; &lt;/script&gt;

&lt;p&gt;Computing the triangle takes quadratic time \(O(n^2)\), since we compute each possible \(k\) for each row (\(n\) rows in total). 
Once the triangle is computed we can simply lookup the binomial coefficient in constant time \(O(1)\)for different \(n\) and \(k\). 
The big problem arises when looking at the space complexity of \(O(n^2)\). 
For some problems \(n\) might be small enough, so there won’t be an issue, but for very large \(n\) we will not have enough memory to store the table, which means we have to find a better approach for those cases.&lt;/p&gt;

&lt;p&gt;There is an easy upgrade in terms of space complexity. 
Each row from Pascal’s Triangle can be calculated by only knowing the previous row. 
This means we only have to keep track of the current row, thus the space complexity is linear \(O(n)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code: Computing single row in Pascal’s Triangle, for any \(m\)&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/46ebb1d310df5f9b5d8c.js?file=pascal_triangle_row.py&quot;&gt; &lt;/script&gt;

&lt;p&gt;Even though this approach allows to calculate larger binomial coefficients due to better space complexity, it still comes with a downside. 
In the first approach we can calculate the binomial coefficient in \(O(1)\), after we have pre-computed Pascal’s Triangle in \(O(n^2)\). 
However in this approach, we need to recalculate the triangle or compute further rows each time a smaller or bigger row \(n\) is asked than the currently computed one. 
Consequently, this approach is expensive when we expect to calculate many different binomial coefficients that are not in the same row of Pascal’s Triangle.&lt;/p&gt;

&lt;h2 id=&quot;2-advanced-approaches-when-m-is-prime&quot;&gt;2. Advanced approaches when \(m\) is prime&lt;/h2&gt;

&lt;p&gt;In most related problems we are asked to calculate \({n \choose k} \mod m\), with \(m\) being a prime number. 
The choice of \(m\) being a prime number is by far no coincidence, since prime number modulus create a field in which certain Theorems hold.&lt;/p&gt;

&lt;h3 id=&quot;using-fermats-little-theorem&quot;&gt;Using Fermat’s Little Theorem&lt;/h3&gt;

&lt;p&gt;We remember that the binomial coefficient can be written as \(\frac{n!}{k!(n-k)!} = \frac{n \cdot (n-1) \cdot \dots \cdot (n-k+1)}{k!}\). 
We can easily calculate the numerator of that equation, since \(((a \mod m) \cdot (b \mod m))\)\( \mod m = (a \cdot b) \mod m\). 
In order to divide the numerator by the denominator, we have to multiply the numerator with the multiplicative inverse of the denominator. 
Lucky for us, if \(m\) is prime, we can easily apply &lt;a href=&quot;https://en.wikipedia.org/wiki/Fermat&apos;s_little_theorem&quot;&gt;Fermat’s little theorem&lt;/a&gt;. 
Through this theorem we know that \(a^{-1} \equiv a^{p-2} \mod p\), with \(p\) being a prime number. 
Consequently, we can easily find the multiplicative inverse through modular exponentiation of \((k!)^{m-2}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code: Using Fermat’s Theorem, for \(m\) prime and \(k &amp;lt; m\)&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/46ebb1d310df5f9b5d8c.js?file=fermat_binom.py&quot;&gt; &lt;/script&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p&gt;Computing the factorial \(n!\) takes \(O(n)\) and computing one multiplicative inverse takes \(O(\log_2 n)\). 
Note, that we implemented two versions here:&lt;/p&gt;

  &lt;p&gt;In the first version, we pre-computed the factorials and the corresponding inverses in an array at the cost of \(O(n)\) memory. 
This pre-computation takes \(O(n \log_2 n)\) time and gives us the advantage of further lookups of binomial coefficients within the same range at constant time \(O(1)\).&lt;/p&gt;

  &lt;p&gt;In the second version, without pre-computed lookups, we re-compute the values each time and only calculate the multiplicative inverse of one denominator, thus having a linear time \(O(n)\) in total each time we want to calculate a binomial coefficient.&lt;/p&gt;

  &lt;p&gt;Whether we use pre-computed tables or not highly depends on \(n\)’s expected size. 
In case we have very large \(n\), pre-computing the factorial and inverse tables with Fermat’s theorem (space complexity \(O(n)\) and runtime of pre-computation \(O(n \log_2 n)\)) might still be too expensive. 
In all other cases, pre-computing is desired since it will save us a lot of time later on. 
In the following I will only show algorithms without pre-computation, since those are also working for very large \(n\), but changing those algorithms to pre-computed versions can be done easily (analogous to the current example), since the core idea is still the same.&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;Note, that this code is only working as long as \(k &amp;lt; m\), since otherwise \(k! \mod m = 0\), which means there is no inverse defined. 
Luckily, with slight modifications we can work around this issue. 
First we compare the degree of \(m\) in numerator and denominator, because the degree in the numerator has to be smaller or equal. 
Further, we cancel out any occurrence of \(m\) in both, numerator and denominator.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code: Using Fermat’s Theorem, for \(m\) prime&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/46ebb1d310df5f9b5d8c.js?file=fermat_binom_advanced.py&quot;&gt; &lt;/script&gt;

&lt;p&gt;We are now able to determine the binomial coefficient in linear time \(O(n)\) as long as the modulo is a prime number. 
We will see in the next sections how we can enhance the computation in terms of time complexity in some scenarios. 
Further, we will see how we can determine the binomial coefficients in case the modulo is not a prime number. 
The algorithms involving Fermat and Pascal are very crucial, since all further approaches that we are going to discuss in this post are relying on them to solve the core computation.&lt;/p&gt;

&lt;h3 id=&quot;using-lucas-theorem&quot;&gt;Using Lucas’ Theorem&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Lucas%27_theorem&quot;&gt;Lucas’ theorem&lt;/a&gt; gives us a great way to break down the computation of one large binomial coefficient into the computation of smaller binomial coefficients. 
In order to do so, we first have to convert the digits of \(n\) and \(k\) into their base \(m\) representation \(n = n_0 + n_1 \cdot m^1 + n_2 \cdot m^2 \dots n_x \cdot m^x\) and \(k = k_0 + k_1 \cdot m^1 + k_2 \cdot m^2 \dots k_x \cdot m^x\). 
We can then define sub problems: \({n \choose k} = \prod_{i=0}^x {n_i \choose k_i} (\mod m)\). 
These problems can then be solved using Fermat’s theorem like we did before.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code: Using Lucas’ + Fermat’s Theorem, for \(m\) prime&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/46ebb1d310df5f9b5d8c.js?file=lucas_binom.py&quot;&gt; &lt;/script&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p&gt;A little side fact: Lucas’ theorem gives an efficient way of determining whether our prime \(m\) is a divisor of the binomial coefficient, without calculating the coefficient itself. 
All we have to do is compare the digits of \(n\) and \(k\) in their base \(m\) representation \(n = n_0 + n_1 \cdot m^1 + n_2 \cdot m^2…\) and \(k = k_0 + k_1 \cdot m^1 + k_2 \cdot m^2 …\) and if in at least one case \(k_i &amp;gt; n_i\), then the product of all sub binomial coefficients would be 0, since \({n \choose k} = 0\), when \(k &amp;gt; n\).&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;We used Lucas’ theorem to first split the problem into smaller binomial coefficients that we could then use to find our solution. 
In order to solve the small coefficients, we used Fermat’s theorem like in the previous section of this post. 
We could have also used Pascal’s Triangle in order to compute these small coefficients. 
Also, in case (n) and (k) are smaller than (m), Lucas’ theorem would not have brought any benefits, because the smallest sub problem would then be the original problem itself. 
However, in that case Lucas’ theorem does only bear the small overhead of bringing \(n\) and \(k\) in base \(m\) representation, which is why in general it is a good approach to first try splitting the problem into smaller sub problems with Lucas’ theorem, then using Pascal’s Triangle or Fermat’s theorem to solve these sub problems.&lt;/p&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p&gt;Remember, in this example we did not use pre-computation, which makes it more efficient when computing only one single very large \(n\). 
Whether we use pre-computed tables or not highly depends on the expected size of \(n\) (which when using Lucas’ theorem, is the biggest prime factor in \(m\)) and whether we expect to calculate many different coefficients. 
In case our sub problems have still very large \(n\), pre-computing the factorial and inverse tables with Fermat’s theorem (space complexity \(O(n)\) and initial runtime \(O(n \log_2 n)\)) might still be too expensive to be feasible. 
In all other cases, pre-computing is desired since it will save us a lot of time later on.&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;All in all, now we have efficient ways of computing large binomial coefficients modulo a prime number.&lt;/p&gt;

&lt;h2 id=&quot;3-ms-prime-factorization-is-square-free&quot;&gt;3. \(m\)’s prime factorization is &lt;a href=&quot;https://en.wikipedia.org/wiki/Square-free_integer&quot;&gt;square-free&lt;/a&gt;&lt;/h2&gt;

&lt;p&gt;What do we do in cases in which \(m\) turns out not to be a prime? 
The answer lies in the prime factorization of \(m\). 
The following method works when \(m\)’s prime factorization is &lt;a href=&quot;https://en.wikipedia.org/wiki/Square-free_integer&quot;&gt;square-free&lt;/a&gt;, e.g. \(6 = 2 \cdot 3\), which means \(6\) is square-free, whereas \(24 = 2^3 \cdot 3\) is not square-free, since the prime \(2\) occurs more than once.&lt;/p&gt;

&lt;p&gt;Lets assume \(m\)’s prime factors are \(m = p_0 \cdot p_1 \dots \cdot p_r\). 
For each prime factor \(p_i\) of \(m\), we can solve \({n \choose k} \mod p_i\), using the approaches we have discussed so far, which leaves us with \(r\) results \(a_0, a_1, \dots, a_r\). 
Through the &lt;a href=&quot;https://en.wikipedia.org/wiki/Chinese_remainder_theorem&quot;&gt;Chinese Remainder Theorem (CRT)&lt;/a&gt; we know that we can find a number \(x\), which solves the following congruences \(x \equiv a_0 \mod p_0\), \(x \equiv a_1 \mod p_1\), \(\dots\), \(x \equiv a_r \mod p_r\).&lt;/p&gt;

&lt;p&gt;Let’s define \(m_i = \frac{p_0 \cdot p_1 \cdot \dots \cdot p_r}{p_i}\). 
We know that \(m_i\) and \(p_i\) must be coprime, then \(gcd(m_i,p_i) = 1\), meaning \(1 = s_i \cdot m_i + t_i \cdot p_i\). 
Using the &lt;a href=&quot;https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm&quot;&gt;Extended Euclidean Algorithm&lt;/a&gt;, we can find such \(s_i\) and \(t_i\). 
Finally, we can find the solution that combines all the congruences to \(x = \sum_{i=0}^r (a_i \cdot m_i \cdot s_i) (\mod \prod_{i=0}^r m_i)\),&lt;/p&gt;

&lt;p&gt;The CRT works as long as \(p_0 \dots p_r\) are co-prime. 
We see, that by applying the CRT to those congruence systems, we can combine them into a single congruence modulo \(m\), which solves our problem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code: Using Lucas’ + Fermat’s + Chinese Remainder Theorem, for (m) with square-free prime factors&lt;/strong&gt;&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/46ebb1d310df5f9b5d8c.js?file=lucas_crt_binom.py&quot;&gt; &lt;/script&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p&gt;Finding the prime factorization of \(m\) is non-trivial and no efficient algorithm is known so far that can solve this problem for large \(m\). 
However, as long as \(m\) has a reasonable size (and that is very likely in those combinatoric problems), finding the prime factorization is feasible. 
You can write your own algorithm or use some online calculators to determine the prime factors. 
Also remember that our current approach is only valid for \(m\) whose prime factors are square-free.&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;Now we are also able to compute large binomial coefficients modulo numbers whose prime factorization is square-free.&lt;/p&gt;

&lt;h2 id=&quot;4-m-has-prime-factors-with-multiplicity-higher-than-1&quot;&gt;4. \(m\) has prime factors with &lt;a href=&quot;https://en.wikipedia.org/wiki/Multiplicity_(mathematics)&quot;&gt;multiplicity&lt;/a&gt; higher than 1&lt;/h2&gt;

&lt;p&gt;Finally, lets have a look at all the remaining possible modulo numbers, namely those containing prime factors with a &lt;a href=&quot;https://en.wikipedia.org/wiki/Multiplicity_(mathematics)&quot;&gt;multiplicity&lt;/a&gt; higher than 1. 
For that purpose we can use Andrew Granville’s &lt;a href=&quot;http://www.dms.umontreal.ca/~andrew/PDF/BinCoeff.pdf&quot;&gt;generalization of Lucas’ Theorem&lt;/a&gt;. 
This theorem also allows prime powers in the factorization of \(m\). 
After applying the theorem, we could then use our other methods to calculate the sub problems and then like before use the Chinese Remainder Theorem to combine the sub solutions into one solution. 
With prime powers allowed, we can then factorize any modulus \(m\), meaning we can find the binomial coefficients modulo any number \(m\). 
I don’t have an implementation ready yet for the generalization of Lucas’ Theorem, but once I have some time I will try to add it to this post.&lt;/p&gt;

&lt;h2 id=&quot;5-quick-summary&quot;&gt;5. Quick Summary&lt;/h2&gt;

&lt;p&gt;We should do the following steps in order to compute large binomial coefficients \({n \choose k} \mod m\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Find prime factors (and multiplicities) \(p_0^{e_0}, \dots p_r^{e_r}\) of \(m\)&lt;/li&gt;
  &lt;li&gt;Use (generalized) Lucas’ Theorem to find all sub problems for each \({n \choose k} \mod p_i^{e_i}\)&lt;/li&gt;
  &lt;li&gt;Solve sub problems \({n \choose k} \mod p_i^{e_i}\) with Fermat’s little theorem or Pascal’s Triangle&lt;/li&gt;
  &lt;li&gt;Use Chinese Remainder Theorem to combine sub results&lt;/li&gt;
&lt;/ul&gt;

&lt;div style=&quot;background: url(/content-images/note-bulb.png) no-repeat scroll left center transparent; color: black; padding: 10px 10px 10px 35px; margin: 15px 0px 15px 0px; background-color: #F2F2F2; border:1px solid grey; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px;}&quot;&gt;

  &lt;p&gt;Remember, if \(p_i &amp;gt; n\), then there are no sub problems and we basically just solve the problem at hand using Fermat’s little theorem or Pascal’s Triangle.&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;That’s it! 
Now we can compute the binomial coefficients for very large numbers for any modulo \(m\).&lt;/p&gt;

</description>
        <pubDate>Thu, 25 Jun 2015 22:15:53 +0000</pubDate>
        <link>http://fishi0x01.devtail.com/weblog/2015/06/25/computing-large-binomial-coefficients-modulo-prime-non-prime/</link>
        <guid isPermaLink="true">http://fishi0x01.devtail.com/weblog/2015/06/25/computing-large-binomial-coefficients-modulo-prime-non-prime/</guid>
        
        
        <category>algorithm</category>
        
        <category>python</category>
        
      </item>
    
      <item>
        <title>Another Python BrainF*** Interpreter</title>
        <description>&lt;p class=&quot;text-justify&quot;&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Brainfuck&quot;&gt;BrainF***&lt;/a&gt; (BF) is a famous esoteric programming language. 
Writing an interpreter for BF is actually easier or should I say at least easier to comprehend than writing an actual BF &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Hello World!&lt;/code&gt; program. 
Even though BF can theoretically be used to write any program, it is not practical to do so because of its low abstraction level. 
I guess that’s one reason why it feels like I find more BF interpreters written in all kinds of languages scattered over many tech blogs rather than actual BF programs. 
Still, since I had a free day, a nice cold drink and the urge to script something I decided to add yet another Python BF interpreter to the web. 
Though for Python BF there are some nice one-liner code-golf-like versions out there, I chose the simpler approach of writing a structured, easy to comprehend version. &lt;!--more--&gt;&lt;/p&gt;

&lt;h2 id=&quot;bf-basics&quot;&gt;BF Basics&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Before we get started on the interpreter code itself, let’s start off with some BF basics.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;In BF you have a memory of usually 30000 cells - also referred to as tape - and each cell holds one byte (0-255). 
You also have exactly one memory pointer initially pointing to the leftmost memory cell. 
Further, you have an instruction pointer keeping track of which operation to execute next.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;BF consists of only the following 8 operations:&lt;/p&gt;

&lt;ul class=&quot;text-justify&quot;&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;gt;&lt;/code&gt;: shift the memory pointer 1 to the right&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;&lt;/code&gt;: shift the memory pointer 1 to the left&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt;: increment byte in cell at memory pointer&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-&lt;/code&gt;: decrement byte in cell at memory pointer&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.&lt;/code&gt;: output byte from cell at memory pointer&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;,&lt;/code&gt;: accept input and store in cell at memory pointer&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[&lt;/code&gt;: loop start: if byte in cell at memory pointer is zero, then jump to corresponding closing bracket &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;]&lt;/code&gt;. 
Otherwise execute the next command.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;]&lt;/code&gt;: loop end: if byte in cell at memory pointer is nonzero, then jump back to corresponding opening bracket &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[&lt;/code&gt;. 
Otherwise execute next command.&lt;/li&gt;
&lt;/ul&gt;

&lt;p class=&quot;text-justify&quot;&gt;As you can see the operations are quite simple and easy to comprehend. 
Apart from that, some additional constraints have to be taken into account:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Memory Borders&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p class=&quot;text-justify&quot;&gt;As I have already mentioned BF usually has 30000 cells. 
The question now is what happens when the memory pointer is shifted beyond those limits? 
One way to handle this is by wrapping the pointer around, meaning when being shifted right from the right-most cell, the pointer goes to the left-most cell and vice versa. 
Another, simpler approach would be to throw a segmentation fault or some other kind of exception.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Memory Space&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p class=&quot;text-justify&quot;&gt;You could initialize a memory with the maximum amount of cells. 
If you only need a very small portion of that memory, than most of the memory was unnecessarily reserved. 
Another way would be to grow the memory on demand until it reaches its maximum allowed value. 
Whenever the pointer is moved to the right and the cell is not initialized yet, we then reserve the memory for that cell. 
The advantage of this method is obviously a more efficient space usage. 
The clear disadvantage is that each reservation costs time and thus influences the overall speed of the BF interpreter.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Argument Input&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p class=&quot;text-justify&quot;&gt;There are 2 major ways to get input. 
The first way is via standard user input via &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;STDIN&lt;/code&gt;. 
It is easy to implement, but for longer repetitive programs quite annoying for the user. 
Another way is to use an extra file with input arguments.&lt;/p&gt;

&lt;h2 id=&quot;bf-loops&quot;&gt;BF Loops&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Most BF operations are very easy to implement and mainly consist of a few pointer movements. 
Depending on whether we decide to use memory wrapping or separate argument input files as described before, the complexity slightly rises, but is still very easy to comprehend.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;The only thing we should have a closer discussion about is the loop implementation. 
A naive way to implement the loop could be to move the instruction pointer until the corresponding closing or opening bracket is found. 
We must be aware of possible nested loops, meaning we have to count the occurrences of each bracket while looking for the matching ones - a stack structure might come in handy at that point. 
However, searching the source code for the corresponding bracket each time we encounter one is rather inefficient. 
At least we should remember the brackets in a map, so next time we can simply lookup the jump to the next instruction without searching. 
We could also pre-parse the code in order to make a map of all matching brackets, even before we start executing the first operation.&lt;/p&gt;

&lt;h2 id=&quot;finally---some-code&quot;&gt;Finally - Some Code&lt;/h2&gt;

&lt;p class=&quot;text-justify&quot;&gt;Finally, let’s have a look at some BF interpreter code!&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/fishi0x01/c47cded22b3271f7e16e.js?file=pybf.py&quot;&gt; &lt;/script&gt;

&lt;p class=&quot;text-justify&quot;&gt;This BF interpreter has no memory wrapping, so whenever the memory pointer moves beyond the limits, a SegFault exception is thrown. 
Further, an optional input file can be used to feed the input BF function &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;,&lt;/code&gt;. 
In case no input file is provided or all bytes have already been read from the input file, the user has to provide input via &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;STDIN&lt;/code&gt;.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;In the first section we simply added some specific exceptions which might occur (such as SegFaults). 
In the second section we define a BF process which holds the context of our BF program. 
This class also implements every allowed BF operation and a code parse function. 
Finally, in the main routine we remove everything from our source code that’s not BF code syntax, then build a context and execute the program. 
Prior to the first operation the code is parsed to get a map of the matching loop brackets.&lt;/p&gt;

&lt;p class=&quot;text-justify&quot;&gt;And finally, here is a BF &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Hello World!&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;hello_world.bf&lt;/strong&gt;&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-brainfuck&quot; data-lang=&quot;brainfuck&quot;&gt;&lt;span class=&quot;nf&quot;&gt;++++++++++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;+++++++&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;++++++++++&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;+++&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;lt;&amp;lt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;++.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;+.&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;+++++++..+++.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;++.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;+++++++++++++++.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;.+++.------.&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;--------.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;+.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;.&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p class=&quot;text-justify&quot;&gt;When giving this code as an argument to our BF interpreter we should be able to see a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Hello World!&lt;/code&gt;.&lt;/p&gt;

</description>
        <pubDate>Mon, 15 Jun 2015 22:21:12 +0000</pubDate>
        <link>http://fishi0x01.devtail.com/weblog/2015/06/15/another-python-bf-interpreter/</link>
        <guid isPermaLink="true">http://fishi0x01.devtail.com/weblog/2015/06/15/another-python-bf-interpreter/</guid>
        
        
        <category>python</category>
        
      </item>
    
  </channel>
</rss>
