<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://www.publysher.nl/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.publysher.nl/" rel="alternate" type="text/html" /><updated>2026-12-05T13:14:22+00:00</updated><id>https://www.publysher.nl/feed.xml</id><title type="html">Yigal Duppen</title><subtitle>Yigal Duppen develops software</subtitle><entry><title type="html">Infra revisited</title><link href="https://www.publysher.nl/devops/2024/09/28/infra-as-repo-revisited.html" rel="alternate" type="text/html" title="Infra revisited" /><published>2024-09-28T00:00:00+00:00</published><updated>2024-09-28T00:00:00+00:00</updated><id>https://www.publysher.nl/devops/2024/09/28/infra-as-repo-revisited</id><content type="html" xml:base="https://www.publysher.nl/devops/2024/09/28/infra-as-repo-revisited.html"><![CDATA[<p>More than ten years ago I wrote a series of articles on provisioning servers using DigitalOcean, Vagrant and SaltStack.
Since then, a lot has changed.</p>

<h2 id="managing-vms-and-local-testing">Managing VMs and local testing</h2>

<p>First of all, I stopped using Vagrant. The idea was to replicate the eventual infrastructure locally, but this just does
not work. Most cloud provider modules cannot be reproduced with just VMs. I now believe it’s better to just spin up a
development infrastructure on the targeted cloud provider, and test against that.</p>

<p>I am now firmly in the <a href="https://www.terraform.io">Terraform</a> camp.</p>

<h2 id="provisioning">Provisioning</h2>

<p>Secondly, I’ve decided that most provisioning tools suck. Tools like Puppet and SaltStack require all kinds of
additional software to be installed on your VMs. Tools like Ansible are slightly better, but you
need to duplicate a lot of information that is already present in Terraform. This can be done, and I’ve actually
done it, but it always feels like a hack.</p>

<p>Finally, those provisioning tools are not as idempotent as they want you to believe. The only way to ensure your
server is exactly what you want it to be, is to destroy and rebuild it over and over again.</p>

<h2 id="cloud-init">Cloud-Init</h2>

<p>Combining this goal with my preference for Terraform results in only one option: <a href="https://cloud-init.io/">Cloud-init</a>.
The upcoming series of articles investigates a non-trivial cloud set-up on DigitalOcean using Terraform and cloud-init.</p>]]></content><author><name></name></author><category term="devops" /><summary type="html"><![CDATA[How to provision a server on DigitalOcean using Terraform and cloud-init]]></summary></entry><entry><title type="html">Infra revisited</title><link href="https://www.publysher.nl/devops/2024/09/28/terraform-getting-started.html" rel="alternate" type="text/html" title="Infra revisited" /><published>2024-09-28T00:00:00+00:00</published><updated>2024-09-28T00:00:00+00:00</updated><id>https://www.publysher.nl/devops/2024/09/28/terraform-getting-started</id><content type="html" xml:base="https://www.publysher.nl/devops/2024/09/28/terraform-getting-started.html"><![CDATA[<p>In this post I’ll provision my first resource on DigitalOcean using Terraform. Most of the post will concern itself
with automating my workflow.</p>

<h2 id="initial-project-setup">Initial project setup</h2>

<p>Let’s start with a nice project directory. I prefer to immediately create them on GitHub. There’s really not much
to say here.</p>

<p>Some people like to start with intricate folder structures. I usually don’t have a clue where I’ll end up, so I tend
not to do this. Instead, everything will be put in the project root initially.</p>

<h2 id="getting-started-with-digitalocean">Getting started with DigitalOcean</h2>

<p>Then, create an account on DigitalOcean and obtain an access token. For now, just give
the access token full permissions – I’ll get back to that later. 
Be on the safe side though, and add an expiry to the token. Store the token in a file called <code class="language-plaintext highlighter-rouge">.env</code> in the project 
directory:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>DIGITALOCEAN_ACCESS_TOKEN=dop_etc_etc_etc
</code></pre></div></div>

<p>Let’s make sure this token never ends up in Git:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">echo</span> .env <span class="o">&gt;&gt;</span> .gitignore
</code></pre></div></div>

<h2 id="getting-started-with-terraform">Getting started with Terraform</h2>

<p>Current best practices suggests to have the following layout for a Terraform project:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>my-project/
    provider.tf    # provider specific settings
    main.tf        # top-level entry point for creating resources
    outputs.tf     # file describing all outputs
    variables.tf   # file describing all inputs 
</code></pre></div></div>

<p>All of these names are conventional. The <code class="language-plaintext highlighter-rouge">.tf</code> extension is the only thing required to have Terraform run out of the box.</p>

<p>First, set up the right Terraform providers in <code class="language-plaintext highlighter-rouge">provider.tf</code>.</p>

<div class="language-terraform highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">terraform</span> <span class="p">{</span>
  <span class="nx">required_providers</span> <span class="p">{</span>
    <span class="nx">digitalocean</span> <span class="o">=</span> <span class="p">{</span>
      <span class="nx">source</span>  <span class="o">=</span> <span class="s2">"digitalocean/digitalocean"</span>
      <span class="nx">version</span> <span class="o">=</span> <span class="s2">"2.42.0"</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And initialize:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>terraform init
</code></pre></div></div>

<p>Let’s create a new DigitalOcean project using Terraform. Mostly because they are free, so not a lot can go wrong. Let’s
set up <code class="language-plaintext highlighter-rouge">main.tf</code></p>

<div class="language-terraform highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">resource</span> <span class="s2">"digitalocean_project"</span> <span class="s2">"main"</span> <span class="p">{</span>
  <span class="nx">name</span>    <span class="o">=</span> <span class="s2">"Terraform Cloud-Init Project"</span>
  <span class="nx">purpose</span> <span class="o">=</span> <span class="s2">"Resources for the Terraform Cloud-Init blogpost"</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And let’s see if everything is supposed to work:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">env</span> <span class="si">$(</span><span class="nb">cat</span> .env<span class="si">)</span> terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  <span class="c"># digitalocean_project.main will be created</span>
  + resource <span class="s2">"digitalocean_project"</span> <span class="s2">"main"</span> <span class="o">{</span>
      + created_at <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
      + <span class="nb">id</span>         <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
      + is_default <span class="o">=</span> <span class="nb">false</span>
      + name       <span class="o">=</span> <span class="s2">"Terraform Cloud-Init Project"</span>
      + owner_id   <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
      + owner_uuid <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
      + purpose    <span class="o">=</span> <span class="s2">"Resources for the Terraform Cloud-Init blogpost"</span>
      + resources  <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
      + updated_at <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
    <span class="o">}</span>

Plan: 1 to add, 0 to change, 0 to destroy.
</code></pre></div></div>

<p>This looks pretty good. Time to actually create this resource:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">env</span> <span class="si">$(</span><span class="nb">cat</span> .env<span class="si">)</span> terraform apply <span class="nt">-auto-approve</span>

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  <span class="c"># digitalocean_project.main will be created</span>
  + resource <span class="s2">"digitalocean_project"</span> <span class="s2">"main"</span> <span class="o">{</span>
      + created_at <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
      + <span class="nb">id</span>         <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
      + is_default <span class="o">=</span> <span class="nb">false</span>
      + name       <span class="o">=</span> <span class="s2">"Terraform Cloud-Init Project"</span>
      + owner_id   <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
      + owner_uuid <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
      + purpose    <span class="o">=</span> <span class="s2">"Resources for the Terraform Cloud-Init blogpost"</span>
      + resources  <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
      + updated_at <span class="o">=</span> <span class="o">(</span>known after apply<span class="o">)</span>
    <span class="o">}</span>

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only <span class="s1">'yes'</span> will be accepted to approve.

  Enter a value: <span class="nb">yes

</span>digitalocean_project.main: Creating...
digitalocean_project.main: Creation <span class="nb">complete </span>after 3s <span class="o">[</span><span class="nb">id</span><span class="o">=</span>eaac494a-8471-4dd6-b805-de6d6307df6b]

Apply <span class="nb">complete</span><span class="o">!</span> Resources: 1 added, 0 changed, 0 destroyed.
</code></pre></div></div>

<p>This too looks good. And sure enough, the project shows up on my DigitalOcean panel.</p>

<p>Time to destroy it.</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">env</span> <span class="si">$(</span><span class="nb">cat</span> .env<span class="si">)</span> terraform destroy <span class="nt">-auto-approve</span>
</code></pre></div></div>

<p>The last step is to make sure all the Terraform generated files do not end up in Git, by adding them to <code class="language-plaintext highlighter-rouge">.gitignore</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>.env
.terraform
.terraform.lock.hcl
terraform.tfstate
terraform.tfstate.backup
</code></pre></div></div>

<p>And that’s Terraform in a nutshell.</p>

<h2 id="automate-everything">Automate everything</h2>

<p>I’m very good at forgetting exact invocations, so I like to put stuff like this in a <code class="language-plaintext highlighter-rouge">Makefile</code>:</p>

<div class="language-makefile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/usr/bin/make
</span><span class="k">include</span><span class="sx"> .env</span>	<span class="c"># make sure the .env variables are present
</span><span class="k">export			</span><span class="c"># magic invocation for the above
</span>
<span class="nl">.PHONY</span><span class="o">:</span>	<span class="nf">help</span>
<span class="nl">help</span><span class="o">:</span>					<span class="c">##</span><span class="nf"> Show this help text</span>
	<span class="p">@</span><span class="nb">grep</span> <span class="nt">-E</span> <span class="nt">-h</span> <span class="s1">'\s##\s'</span> <span class="p">$(</span>MAKEFILE_LIST<span class="p">)</span> | <span class="nb">awk</span> <span class="s1">'BEGIN {FS= ":.*?## "} {printf "%-20s %s\n", $$1, $$2}'</span>

<span class="nl">.PHONY</span><span class="o">:</span>	<span class="nf">clean</span>
<span class="nl">clean</span><span class="o">:</span>					<span class="c">##</span><span class="nf"> Clean the current plan file</span>
	<span class="nb">rm</span> <span class="nt">-f</span> plan.out

<span class="nl">.PHONY</span><span class="o">:</span>	<span class="nf">init</span>
<span class="nl">init</span><span class="o">:</span>					<span class="c">##</span><span class="nf"> (Re)initialize Terraform providers</span>
	terraform init

<span class="nl">.PHONY</span><span class="o">:</span>	<span class="nf">plan</span>
<span class="nl">plan</span><span class="o">:</span>	<span class="nf">init plan.out	</span><span class="c">##</span><span class="nf"> Generate the infrastructure plan</span>

<span class="nl">plan.out</span><span class="o">:</span>
	terraform plan <span class="nt">-out</span><span class="o">=</span><span class="nv">$@</span>

<span class="nl">.PHONY</span><span class="o">:</span> <span class="nf">check</span>
<span class="nl">check</span><span class="o">:</span>  <span class="nf">init            </span><span class="c">##</span><span class="nf"> Check for configuration drift</span>
	terraform plan <span class="nt">-detailed-exitcode</span>

<span class="nl">.PHONY</span><span class="o">:</span> <span class="nf">apply</span>
<span class="nl">apply</span><span class="o">:</span>	<span class="nf">plan.out		</span><span class="c">##</span><span class="nf"> Apply the plan and create the infrastructure</span>
	terraform apply plan.out

<span class="nl">.PHONY</span><span class="o">:</span>	<span class="nf">destroy</span>
<span class="nl">destroy</span><span class="o">:</span>	<span class="nf">clean		</span><span class="c">##</span><span class="nf"> Destroy the infrastructure</span>
	terraform destroy <span class="nt">-auto-approve</span>

<span class="nl">.PHONY</span><span class="o">:</span>	<span class="nf">validate</span>
<span class="nl">validate</span><span class="o">:</span>				<span class="c">##</span><span class="nf"> Validate the Terraform files</span>
	terraform <span class="nb">fmt</span>
	terraform validate
</code></pre></div></div>

<p>Yes, this is basically a glorified bash script, but I like it. I stole the <code class="language-plaintext highlighter-rouge">make help</code> target from 
<a href="https://victoria.dev/posts/how-to-create-a-self-documenting-makefile/">Victoria</a>.</p>

<p>Some typical invocations:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>make <span class="nb">help</span>        <span class="c"># in case I forgot</span>
<span class="nv">$ </span>make validate    <span class="c"># this should eventually end up in my pre-commit</span>
<span class="nv">$ </span>make clean apply <span class="c"># bring the infrastructure up to date</span>
<span class="nv">$ </span>make destroy     <span class="c"># destroy the infrastructure  </span>
</code></pre></div></div>

<h2 id="automate-even-more">Automate even more</h2>

<p>I’m a big fan of <a href="https://pre-commit.com/">pre-commit</a>. This tool basically automates the management of pre-commit 
hooks, doing some basic checks before you can even commit your changes.</p>

<p>The <code class="language-plaintext highlighter-rouge">.pre-commit-config.yaml</code> file looks like this:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">repos</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">repo</span><span class="pi">:</span> <span class="s">https://github.com/antonbabenko/pre-commit-terraform</span>
    <span class="na">rev</span><span class="pi">:</span> <span class="s">v1.96.1</span>
    <span class="na">hooks</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">id</span><span class="pi">:</span> <span class="s">terraform_fmt</span>
      <span class="pi">-</span> <span class="na">id</span><span class="pi">:</span> <span class="s">terraform_validate</span>
</code></pre></div></div>

<p>Run <code class="language-plaintext highlighter-rouge">pre-commit install</code> to update the hooks and never commit horrible code again. There are many more pre-commit hooks, 
but for now this will suffice.</p>]]></content><author><name></name></author><category term="devops" /><summary type="html"><![CDATA[How to provision a server on DigitalOcean using Terraform and cloud-init]]></summary></entry><entry><title type="html">Infra as a Repo: Securing your infrastructure with Salt</title><link href="https://www.publysher.nl/devops/2013/08/31/infra-as-repo-securing-your.html" rel="alternate" type="text/html" title="Infra as a Repo: Securing your infrastructure with Salt" /><published>2013-08-31T00:00:00+00:00</published><updated>2013-08-31T00:00:00+00:00</updated><id>https://www.publysher.nl/devops/2013/08/31/infra-as-repo-securing-your</id><content type="html" xml:base="https://www.publysher.nl/devops/2013/08/31/infra-as-repo-securing-your.html"><![CDATA[<p>Provisioning servers on <a href="https://www.digitalocean.com/?refcode=8d8ff680bec5">DigitalOcean</a> like a king is one thing, but let’s be honest: <a href="http://dandydev.net/blog/crashing-servers-and-riding-waves#.UiH0PGTOmwY">default installations don’t provide
a lot of security</a>. So I’ve spent some time to manage the security on my provisioned boxes. This post (and
probably the next as well) will show you how I used <a href="http://saltstack.com/">SaltStack</a> to secure my infrastructure.</p>

<h2 id="the-goal">The goal</h2>

<blockquote>
  <p>Given the master/minion set-up from the previous posts, I want to have a running firewall which:</p>

  <ul>
    <li>enables SSH access</li>
    <li>enables minion/master communication</li>
    <li>enables HTTP(S) access</li>
  </ul>
</blockquote>

<h2 id="quick-fix">Quick Fix</h2>
<p>The first step was an easy one. In <a href="http://blog.publysher.nl/2013/08/infra-as-repo-separating-master-from.html">my previous post</a> I introduced a Makefile to create a public-key
infrastructure; subsequently, the keys were securely distributed using the <a href="https://github.com/saltstack/salty-vagrant">salty-vagrant</a> plugin.</p>

<p>Unfortunately, I forgot that the directory in which your <code class="language-plaintext highlighter-rouge">Vagrantfile</code> resides is automatically shared over all machines.
Which means that in practice, I started out with carefully distributing my secret private keys, only to upload them to
all my hosts in the next step.</p>

<p>Luckily, this was easily fixed by the following line in my <code class="language-plaintext highlighter-rouge">Vagrantfile</code>:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">synced_folder</span> <span class="s1">'shared/'</span><span class="p">,</span> <span class="s1">'/vagrant/'</span></code></pre></figure>

<p>Phew.</p>

<h2 id="adding-a-firewall">Adding a Firewall</h2>
<p>The next step was a bit more complicated: adding firewall rules. Although Salt provides an <a href="http://docs.saltstack.com/ref/states/all/salt.states.iptables.html#module-salt.states.iptables">iptables module</a>,
I decided to go for <a href="https://help.ubuntu.com/community/UFW">ufw</a>. Partially because I like to be contrarian, but mostly because the UFW guys know more
about firewalls than me.</p>

<p>So, what to do when Salt does not provide a module for your needs? My first attempt looked something like this.</p>

<p><code class="language-plaintext highlighter-rouge">salt/roots/salt/firewall/base.sls</code>:</p>

<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="na">ufw</span><span class="pi">:</span>
  <span class="na">pkg</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="s">installed</span>
  <span class="na">service</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="s">running</span>
    <span class="pi">-</span> <span class="na">require</span><span class="pi">:</span>
       <span class="pi">-</span> <span class="na">cmd.run</span><span class="pi">:</span> <span class="s">ufw-enable</span>

<span class="c1"># Enable</span>
<span class="na">ufw-enable</span><span class="pi">:</span>
  <span class="na">cmd.run</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">ufw enable</span>
    <span class="pi">-</span> <span class="na">require</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">pkg</span><span class="pi">:</span> <span class="s">ufw</span>

<span class="c1"># SSH</span>
<span class="na">ufw-ssh</span><span class="pi">:</span>
  <span class="na">cmd.run</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">ufw allow SSH</span>
    <span class="pi">-</span> <span class="na">require</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">pkg</span><span class="pi">:</span> <span class="s">ufw</span>
    <span class="pi">-</span> <span class="na">watch_in</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">service</span><span class="pi">:</span> <span class="s">ufw</span></code></pre></figure>

<p><code class="language-plaintext highlighter-rouge">salt/roots/salt/firewall/salt-master.sls</code>:</p>

<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="na">ufw-salt-master</span><span class="pi">:</span>
  <span class="na">cmd.run</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">ufw allow from $(getent ahosts nginx01.intranet | awk 'NR==1 {print $1}') to any port 4505,4506 proto tcp</span>
    <span class="pi">-</span> <span class="na">require</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">pkg</span><span class="pi">:</span> <span class="s">ufw</span>
    <span class="pi">-</span> <span class="na">watch_in</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">service</span><span class="pi">:</span> <span class="s">ufw</span></code></pre></figure>

<p><code class="language-plaintext highlighter-rouge">salt/roots/top.sls</code>:</p>

<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="s1">'</span><span class="s">*'</span><span class="err">:</span>
  <span class="pi">-</span> <span class="s">firewall.base</span>
<span class="s1">'</span><span class="s">salt.intranet'</span><span class="err">:</span>
  <span class="pi">-</span> <span class="s">firewall.salt-master</span></code></pre></figure>

<p>And, to be honest, this is not a bad first attempt. I define a base firewall which allows SSH access and enables UFW;
I then proceeded to define a specific rule for the salt master which allows TCP connections to the salt master 0MQ ports
4505 and 4506, and I applied these rules to the correct hosts in <code class="language-plaintext highlighter-rouge">top.sls</code>.</p>

<p>Still, this set-up has two major problems. First of all, because the commands are <a href="http://docs.saltstack.com/ref/states/all/salt.states.cmd.html">stateless</a>, they are run
every time the highstate is ensured. Not a huge problem in itself, but not the most beautiful solution either.</p>

<p>Secondly, in order to only allow 0MQ access from my own hosts, I had to resort to a dirty trick; since the IP address
of the various hosts changes per provider, I really need to allow access based on hostname, something that is not
supported by UFW out of the box. Hence the somewhat dubious <code class="language-plaintext highlighter-rouge">$(getent ahosts nginx01.intranet)</code> fragment in my
<code class="language-plaintext highlighter-rouge">salt-master.sls</code>.</p>

<h2 id="creating-salt-modules">Creating Salt modules</h2>
<p>Whenever you have a need that is not covered by the basic Salt modules, the Salt documentation suggests you create
your own modules. And wow, that’s easy. (Footnote: my first attempt at provisioning was based on <a href="https://puppetlabs.com/">Puppet</a>; customizing
Puppet requires you to do some weird magic in some kind of almost-language called Ruby. It’s no fun.)</p>

<p>Salt distinguishes two kind of modules: <a href="http://docs.saltstack.com/ref/#minion-execution-modules">execution modules</a> (do stuff) and <a href="http://docs.saltstack.com/ref/states/writing.html">state modules</a> (ensure that stuff is
configured as desired). Let’s have a look at my UFW execution module:</p>

<p><code class="language-plaintext highlighter-rouge">salt/roots/salt/_modules/ufw.py</code>:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="sh">"""</span><span class="s">
Execution module for UFW.
</span><span class="sh">"""</span>
<span class="k">def</span> <span class="nf">is_enabled</span><span class="p">():</span>
    <span class="n">cmd</span> <span class="o">=</span> <span class="sh">'</span><span class="s">ufw status | grep </span><span class="sh">"</span><span class="s">Status: active</span><span class="sh">"'</span>
    <span class="n">out</span> <span class="o">=</span> <span class="n">__salt__</span><span class="p">[</span><span class="sh">'</span><span class="s">cmd.run</span><span class="sh">'</span><span class="p">](</span><span class="n">cmd</span><span class="p">)</span>
    <span class="k">return</span> <span class="bp">True</span> <span class="k">if</span> <span class="n">out</span> <span class="k">else</span> <span class="bp">False</span>


<span class="k">def</span> <span class="nf">set_enabled</span><span class="p">(</span><span class="n">enabled</span><span class="p">):</span>
    <span class="n">cmd</span> <span class="o">=</span> <span class="sh">'</span><span class="s">ufw --force enable</span><span class="sh">'</span> <span class="k">if</span> <span class="n">enabled</span> <span class="k">else</span> <span class="sh">'</span><span class="s">ufw disable</span><span class="sh">'</span>
    <span class="n">__salt__</span><span class="p">[</span><span class="sh">'</span><span class="s">cmd.run</span><span class="sh">'</span><span class="p">](</span><span class="n">cmd</span><span class="p">)</span>


<span class="k">def</span> <span class="nf">add_rule</span><span class="p">(</span><span class="n">rule</span><span class="p">):</span>
    <span class="n">cmd</span> <span class="o">=</span> <span class="sh">"</span><span class="s">ufw </span><span class="sh">"</span> <span class="o">+</span> <span class="n">rule</span>
    <span class="n">out</span> <span class="o">=</span> <span class="n">__salt__</span><span class="p">[</span><span class="sh">'</span><span class="s">cmd.run</span><span class="sh">'</span><span class="p">](</span><span class="n">cmd</span><span class="p">)</span>
    <span class="n">__salt__</span><span class="p">[</span><span class="sh">'</span><span class="s">cmd.run</span><span class="sh">'</span><span class="p">](</span><span class="sh">"</span><span class="s">ufw reload</span><span class="sh">"</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">out</span></code></pre></figure>

<p>Complicated, no? By putting my execution module in the <code class="language-plaintext highlighter-rouge">_modules/</code> directory, this new execution module is automatically
synced to all minions. (If not, use <code class="language-plaintext highlighter-rouge">salt '*' saltutil.sync_all</code> to force a new sync). This module is now available
like any salt module: <code class="language-plaintext highlighter-rouge">salt '*' ufw.is_enabled</code> gives you a nice overview of all minions that have UFW enabled.</p>

<p>Note how I used the <code class="language-plaintext highlighter-rouge">__salt__</code> dict to defer the actual work to the existing <code class="language-plaintext highlighter-rouge">cmd.run</code> function. Quite a nice feature.</p>

<p>The state module turned out to be a bit more complicated, but mostly because it has to do a lot of bookkeeping:</p>

<p><code class="language-plaintext highlighter-rouge">salt/roots/salt/_states/ufw.py</code>:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="c1"># boilerplate &amp; helpers...
</span>
<span class="k">def</span> <span class="nf">enabled</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">__salt__</span><span class="p">[</span><span class="sh">'</span><span class="s">ufw.is_enabled</span><span class="sh">'</span><span class="p">]():</span>
        <span class="k">return</span> <span class="nf">_unchanged</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="sh">"</span><span class="s">UFW is already enabled</span><span class="sh">"</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">__opts__</span><span class="p">[</span><span class="sh">'</span><span class="s">test</span><span class="sh">'</span><span class="p">]:</span>
        <span class="k">return</span> <span class="nf">_test</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="sh">"</span><span class="s">UFW will be enabled</span><span class="sh">"</span><span class="p">)</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="n">__salt__</span><span class="p">[</span><span class="sh">'</span><span class="s">ufw.set_enabled</span><span class="sh">'</span><span class="p">](</span><span class="bp">True</span><span class="p">)</span>
    <span class="nf">except </span><span class="p">(</span><span class="n">CommandExecutionError</span><span class="p">,</span> <span class="n">CommandNotFoundError</span><span class="p">)</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
        <span class="k">return</span> <span class="nf">_error</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">e</span><span class="p">.</span><span class="n">message</span><span class="p">)</span>

    <span class="k">return</span> <span class="nf">_changed</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="sh">"</span><span class="s">UFW is enabled</span><span class="sh">"</span><span class="p">,</span> <span class="n">enabled</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>


<span class="k">def</span> <span class="nf">allowed</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">app</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">protocol</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span>
            <span class="n">from_addr</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">from_port</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">to_addr</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">to_port</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>

    <span class="n">rule</span> <span class="o">=</span> <span class="nf">_as_rule</span><span class="p">(</span><span class="sh">"</span><span class="s">allow</span><span class="sh">"</span><span class="p">,</span> <span class="n">app</span><span class="o">=</span><span class="n">app</span><span class="p">,</span> <span class="n">protocol</span><span class="o">=</span><span class="n">protocol</span><span class="p">,</span>
                   <span class="n">from_addr</span><span class="o">=</span><span class="n">from_addr</span><span class="p">,</span> <span class="n">from_port</span><span class="o">=</span><span class="n">from_port</span><span class="p">,</span>
                   <span class="n">to_addr</span><span class="o">=</span><span class="n">to_addr</span><span class="p">,</span> <span class="n">to_port</span><span class="o">=</span><span class="n">to_port</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">__opts__</span><span class="p">[</span><span class="sh">'</span><span class="s">test</span><span class="sh">'</span><span class="p">]:</span>
        <span class="k">return</span> <span class="nf">_test</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="sh">"</span><span class="s">{0}: {1}</span><span class="sh">"</span><span class="p">.</span><span class="nf">format</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">rule</span><span class="p">))</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="n">out</span> <span class="o">=</span> <span class="n">__salt__</span><span class="p">[</span><span class="sh">'</span><span class="s">ufw.add_rule</span><span class="sh">'</span><span class="p">](</span><span class="n">rule</span><span class="p">)</span>
    <span class="nf">except </span><span class="p">(</span><span class="n">CommandExecutionError</span><span class="p">,</span> <span class="n">CommandNotFoundError</span><span class="p">)</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
        <span class="k">return</span> <span class="nf">_error</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">e</span><span class="p">.</span><span class="n">message</span><span class="p">)</span>

    <span class="n">changes</span> <span class="o">=</span> <span class="bp">False</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">out</span><span class="p">.</span><span class="nf">split</span><span class="p">(</span><span class="sh">'</span><span class="se">\n</span><span class="sh">'</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">line</span><span class="p">.</span><span class="nf">startswith</span><span class="p">(</span><span class="sh">"</span><span class="s">Skipping</span><span class="sh">"</span><span class="p">):</span>
            <span class="k">continue</span>
        <span class="k">if</span> <span class="n">line</span><span class="p">.</span><span class="nf">startswith</span><span class="p">(</span><span class="sh">"</span><span class="s">Rule added</span><span class="sh">"</span><span class="p">)</span> <span class="ow">or</span> <span class="n">line</span><span class="p">.</span><span class="nf">startswith</span><span class="p">(</span><span class="sh">"</span><span class="s">Rules updated</span><span class="sh">"</span><span class="p">):</span>
            <span class="n">changes</span> <span class="o">=</span> <span class="bp">True</span>
            <span class="k">break</span>
        <span class="k">return</span> <span class="nf">_error</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">line</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">changes</span><span class="p">:</span>
        <span class="k">return</span> <span class="nf">_changed</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="sh">"</span><span class="s">{0} allowed</span><span class="sh">"</span><span class="p">.</span><span class="nf">format</span><span class="p">(</span><span class="n">name</span><span class="p">),</span> <span class="n">rule</span><span class="o">=</span><span class="n">rule</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="nf">_unchanged</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="sh">"</span><span class="s">{0} was already allowed</span><span class="sh">"</span><span class="p">.</span><span class="nf">format</span><span class="p">(</span><span class="n">name</span><span class="p">))</span></code></pre></figure>

<p>If you’re interested in the helpers and boilerplate, <a href="https://github.com/publysher/infra-example-nginx/blob/72837a9cb5cb01e5dab9d3ccfcbf5995a4dcf934/salt/roots/salt/_states/ufw.py">look here</a>.</p>

<h2 id="the-final-rules">The final rules</h2>

<p>Using these brand new modules, the new SLS files looked lot more like proper state files.</p>

<p><code class="language-plaintext highlighter-rouge">salt/roots/salt/firewall/base.sls</code>:</p>

<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="na">ufw</span><span class="pi">:</span>
  <span class="na">pkg</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="s">installed</span>
  <span class="na">ufw.enabled</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">require</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">pkg</span><span class="pi">:</span> <span class="s">ufw</span>


<span class="na">ufw-ssh</span><span class="pi">:</span>
  <span class="na">ufw.allowed</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">protocol</span><span class="pi">:</span> <span class="s">tcp</span>
    <span class="pi">-</span> <span class="na">to_port</span><span class="pi">:</span> <span class="s">ssh</span>
    <span class="pi">-</span> <span class="na">require</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">pkg</span><span class="pi">:</span> <span class="s">ufw</span></code></pre></figure>

<p>Reprovisioning the VM now behaves as expected – enabling the firewall and adding SSH is executed only once. Furthermore,
the Salt master config has become much more readable:</p>

<p><code class="language-plaintext highlighter-rouge">salt/roots/salt/firewall/salt-master.sls</code>:</p>

<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="na">include</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="s">firewall.base</span></code></pre></figure>

<p>Note how I’ve sneakily enabled pillar data as well. Deducing the configuration for <code class="language-plaintext highlighter-rouge">firewall/http.sls</code> is left as
an exercise to the reader (<a href="https://github.com/publysher/infra-example-nginx/blob/develop/salt/roots/salt/firewall/http.sls">hint</a>).</p>

<h2 id="conclusion">Conclusion</h2>

<p>Managing your firewall with Salt is not that hard; it requires some module magic, but that is very easy to do. Of course,
having a firewall is not enough; stay tuned for the next post where I will add more security measures.</p>

<p><em>Don’t forget: <a href="https://github.com/publysher/infra-example-nginx">my infra is a repo</a>, so go ahead and fork it</em></p>]]></content><author><name></name></author><category term="devops" /><summary type="html"><![CDATA[How to secure your servers with Salt.]]></summary></entry><entry><title type="html">Infra as a Repo: Separating the Master from the Minion</title><link href="https://www.publysher.nl/devops/2013/08/11/infra-as-repo-separating-master-from.html" rel="alternate" type="text/html" title="Infra as a Repo: Separating the Master from the Minion" /><published>2013-08-11T00:00:00+00:00</published><updated>2013-08-11T00:00:00+00:00</updated><id>https://www.publysher.nl/devops/2013/08/11/infra-as-repo-separating-master-from</id><content type="html" xml:base="https://www.publysher.nl/devops/2013/08/11/infra-as-repo-separating-master-from.html"><![CDATA[<p>Life can be good. After <a href="http://blog.publysher.nl/2013/08/infra-as-repo-adding-salt-master.html">my previous success in provisioning a master/minion set-up</a>, the next logical step was
to introduce a separate master VM. This post explains how I did it. It will be a relatively short post, because it
turned out to be ridiculously easy.</p>

<h2 id="the-goal">The goal</h2>

<blockquote>
  <p>Given the current single-server master/minion setup, I want to recreate the same situation with two different
machines: one Salt master which only functions as a Salt master, and one Salt minion that runs Nginx.</p>
</blockquote>

<p>How hard can this be?</p>

<h2 id="a-second-vm">A second VM</h2>

<p><a href="http://www.vagrantup.com">Vagrant</a> is built to provision multiple VMs from the same file, so I started by using that feature:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># ...</span>
<span class="c1"># SALT is the salt master</span>
<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:salt</span> <span class="k">do</span> <span class="o">|</span><span class="n">node</span><span class="o">|</span>
    <span class="n">set_network</span><span class="p">(</span><span class="n">node</span><span class="p">,</span> <span class="s1">'10.1.14.50'</span><span class="p">,</span> <span class="sx">%w(salt.intranet salt)</span><span class="p">)</span>
<span class="k">end</span>

<span class="c1"># NGINX01 is a web server</span>
<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:nginx01</span> <span class="k">do</span> <span class="o">|</span><span class="n">node</span><span class="o">|</span>
    <span class="n">set_network</span><span class="p">(</span><span class="n">node</span><span class="p">,</span> <span class="s1">'10.1.14.100'</span><span class="p">,</span> <span class="sx">%w(nginx01.intranet nginx01)</span><span class="p">)</span>
<span class="k">end</span></code></pre></figure>

<p>The <code class="language-plaintext highlighter-rouge">set_network</code> function is an expanded version of the <code class="language-plaintext highlighter-rouge">set_host_aliases</code> function from the <a href="http://blog.publysher.nl/2013/08/infra-as-repo-adding-salt-master.html">previous post</a>.
And that’s it – running <code class="language-plaintext highlighter-rouge">vagrant up</code> will now spin up two virtual machines on my local computer, each with their own
IP address and host names.</p>

<h2 id="provisioning-the-master">Provisioning the master</h2>

<p>The Salt machine is meant to be provisioned as a salt master. I already knew how to do that, so this was easily
implemented:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># SALT is the salt master</span>
<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:salt</span> <span class="k">do</span> <span class="o">|</span><span class="n">node</span><span class="o">|</span>
    <span class="n">set_network</span><span class="p">(</span><span class="n">node</span><span class="p">,</span> <span class="s1">'10.1.14.50'</span><span class="p">,</span> <span class="sx">%w(salt.intranet salt)</span><span class="p">)</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">synced_folder</span> <span class="s1">'salt/roots/'</span><span class="p">,</span> <span class="s1">'/srv/'</span>

    <span class="c1"># Salt-master provisioning</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:salt</span> <span class="k">do</span> <span class="o">|</span><span class="n">salt</span><span class="o">|</span>
        <span class="n">salt</span><span class="p">.</span><span class="nf">bootstrap_script</span> <span class="o">=</span> <span class="s1">'lib/salt-bootstrap/bootstrap-salt.sh'</span>

        <span class="n">salt</span><span class="p">.</span><span class="nf">install_master</span> <span class="o">=</span> <span class="kp">true</span>
        <span class="n">salt</span><span class="p">.</span><span class="nf">run_highstate</span> <span class="o">=</span> <span class="kp">false</span>

        <span class="n">salt</span><span class="p">.</span><span class="nf">minion_key</span> <span class="o">=</span> <span class="s1">'build/keys/salt.intranet.pem'</span>
        <span class="n">salt</span><span class="p">.</span><span class="nf">minion_pub</span> <span class="o">=</span> <span class="s1">'build/keys/salt.intranet.pub'</span>

        <span class="n">salt</span><span class="p">.</span><span class="nf">master_key</span> <span class="o">=</span> <span class="s1">'build/keys/master.pem'</span>
        <span class="n">salt</span><span class="p">.</span><span class="nf">master_pub</span> <span class="o">=</span> <span class="s1">'build/keys/master.pub'</span>

        <span class="n">salt</span><span class="p">.</span><span class="nf">seed_master</span> <span class="o">=</span> <span class="p">{</span>
            <span class="s1">'salt.intranet'</span> <span class="o">=&gt;</span> <span class="s1">'build/keys/salt.intranet.pub'</span><span class="p">,</span>
            <span class="s1">'nginx01.intranet'</span> <span class="o">=&gt;</span> <span class="s1">'build/keys/nginx01.intranet.pub'</span>
        <span class="p">}</span>
    <span class="k">end</span>

    <span class="c1"># And explicitly call the highstate on this one</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:shell</span><span class="p">,</span> <span class="ss">:inline</span> <span class="o">=&gt;</span> <span class="s1">'sleep 60; salt-call state.highstate'</span>
<span class="k">end</span></code></pre></figure>

<p>If this looks vaguely familiar, you’ve obviously read my <a href="http://blog.publysher.nl/2013/08/infra-as-repo-adding-salt-master.html">previous post</a>. If not, go ahead and read it.
The only difference is the addition of a new public/private key-pair for this machine.</p>

<p>This resulted in my master VM being provisioned as a Salt master and Nginx server. Wait. Nginx server? The <code class="language-plaintext highlighter-rouge">top.sls</code>
file needed a little tweaking as well.</p>

<figure class="highlight"><pre><code class="language-yaml" data-lang="yaml"><span class="na">base</span><span class="pi">:</span>
    <span class="s1">'</span><span class="s">nginx01.intranet'</span><span class="err">:</span>
        <span class="pi">-</span> <span class="s">nginx</span></code></pre></figure>

<p>Now my VM was provisioned as desired.</p>

<h2 id="provisioning-the-minion">Provisioning the minion</h2>

<p>I told you it was easy:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby">   
<span class="c1"># NGINX01 is a web server</span>
<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:nginx01</span> <span class="k">do</span> <span class="o">|</span><span class="n">node</span><span class="o">|</span>
    <span class="n">set_network</span><span class="p">(</span><span class="n">node</span><span class="p">,</span> <span class="s1">'10.1.14.100'</span><span class="p">,</span> <span class="sx">%w(nginx01.intranet nginx01)</span><span class="p">)</span>

    <span class="c1"># Salt-minion provisioning</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:salt</span> <span class="k">do</span> <span class="o">|</span><span class="n">salt</span><span class="o">|</span>
        <span class="n">salt</span><span class="p">.</span><span class="nf">bootstrap_script</span> <span class="o">=</span> <span class="s1">'lib/salt-bootstrap/bootstrap-salt.sh'</span>
        <span class="n">salt</span><span class="p">.</span><span class="nf">run_highstate</span> <span class="o">=</span> <span class="kp">true</span>
        <span class="n">salt</span><span class="p">.</span><span class="nf">minion_key</span> <span class="o">=</span> <span class="s1">'build/keys/nginx01.intranet.pem'</span>
        <span class="n">salt</span><span class="p">.</span><span class="nf">minion_pub</span> <span class="o">=</span> <span class="s1">'build/keys/nginx01.intranet.pub'</span>
    <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p>And that’s it. Calling <code class="language-plaintext highlighter-rouge">vagrant up</code> now spins up two VMs: one salt master and one minion that runs as an Nginx server.</p>

<p>Mission Accomplished!</p>

<h2 id="deploying-to-digital-ocean">Deploying to Digital Ocean</h2>

<p><a href="http://www.imdb.com/title/tt0084967/quotes?item=qt0378851">I love it when a plan comes together</a>. You know the drill: <code class="language-plaintext highlighter-rouge">vagrant up --provider=digital_ocean</code> and we’re good to go.
Reclining in my comfy chair I could see my two machines come up somewhere in a hosting center in New York.</p>

<p><strong>WARNING</strong>: <a href="https://www.digitalocean.com/?refcode=8d8ff680bec5">Digital Ocean</a> VMs cost money. Since I started this series, I’ve built up a bill of $2.60.
Don’t try this if you’re really really really broke. In all other cases, they provide good value for money.</p>

<p><em>Don’t forget: <a href="https://github.com/publysher/infra-example-nginx">my infra is a repo</a>, so go ahead and fork it</em></p>]]></content><author><name></name></author><category term="devops" /><summary type="html"><![CDATA[How to provision a separate Salt master on Digital Ocean.]]></summary></entry><entry><title type="html">Infra as a Repo: Adding a Salt master</title><link href="https://www.publysher.nl/devops/2013/08/09/infra-as-repo-adding-salt-master.html" rel="alternate" type="text/html" title="Infra as a Repo: Adding a Salt master" /><published>2013-08-09T00:00:00+00:00</published><updated>2013-08-09T00:00:00+00:00</updated><id>https://www.publysher.nl/devops/2013/08/09/infra-as-repo-adding-salt-master</id><content type="html" xml:base="https://www.publysher.nl/devops/2013/08/09/infra-as-repo-adding-salt-master.html"><![CDATA[<p>After I <a href="http://blog.publysher.nl/2013/07/infra-as-repo-using-vagrant-and-salt.html">managed to provision an Nginx server</a> using a masterless Salt setup, I felt it was time to
introduce a master. This proved to be a frustrating challenge, but in the end I managed to do it. This post
describes how I did it. It might save you some time.</p>

<h2 id="the-goal">The goal</h2>

<blockquote>
  <p>Given the current single-server setup, I want to reach the exact same result using a Salt master. The master
should run on the Nginx server itself.</p>
</blockquote>

<p>How hard can it be?</p>

<h2 id="pki-the-problem">PKI: The problem</h2>

<p>Salt relies on a <a href="http://en.wikipedia.org/wiki/Public-key_infrastructure">public-key infrastructure</a> to let the minions communicate with the master. This means that
every minion has its own public/private key pair, and that the master knows the public key of every minion. Generating
key pairs is not very complex, but distributing keys is.</p>

<p>The private key of the minion</p>

<ol>
  <li>Must <em>only</em> reside on the minion</li>
  <li>Must be <em>securely</em> transfered to the master</li>
  <li>Must be <em>explicitly</em> accepted by the master</li>
  <li>Must be accepted <em>before</em> the provisioning starts</li>
  <li>Can <em>not</em> reside in my Git repo</li>
</ol>

<p>The <a href="https://salt.readthedocs.org/en/latest/topics/tutorials/preseed_key.html">Salt documentation</a> describes the basic concept of preseeding, but it’s severely lacking when you try
to find a solution for all five requirements above. The <a href="https://github.com/saltstack/salty-vagrant">Salty Vagrant documentation</a> provides some
help, but more on that later.</p>

<h2 id="pki-the-short-answer">PKI: The short answer</h2>

<p>I have devised the following solution to the problem of preseeding the Salt master with minion keys:</p>

<ol>
  <li>Use <code class="language-plaintext highlighter-rouge">make</code> and the <code class="language-plaintext highlighter-rouge">openssl</code> tools to create all public/private key pairs in a separate directory and
exclude this directory using <code class="language-plaintext highlighter-rouge">.gitignore</code></li>
  <li>Use the Salty Vagrant plugin to distribute the correct keys to the correct minions and to preseed the master with
the public keys</li>
</ol>

<p>This violates the first requirement, since the private keys now reside on the computer building the infrastructure and
on the minion that is being built, but for now that is acceptable. The second requirement is probably fulfilled –
I hope and assume that Vagrant syncs its files over SSH. The third and fourth requirement are taken care of by the
Salty Vagrant plugin. The last requirement is fixed by providing a means to generate the keys, instead of storing the
keys themselves in my Git repository.</p>

<p>“But what if you lose the keys?”, you might ask. This is actually a funny thing. If I lose the keys, for example by
accidentally typing <code class="language-plaintext highlighter-rouge">make clean</code>, I just have to regenerate them and rebuild my infrastructure. And since my
infrastructure is <em>designed</em> to be rebuilt from scratch over and over again, this is actually not a problem at all.
At least for now. I might revisit this opinion when my infrastructures grows beyond twenty servers.</p>

<h2 id="pki-the-hard-part">PKI: The hard part</h2>

<p>Of course, this all fell apart when I tried to implement this. As it happens, the Salty Vagrant documentation refers
to the Git HEAD, not to the official v0.4.0 you ordinarily install. Furthermore, there is a problem with the current
HEAD where preseeding is done incorrectly. There is a <a href="https://github.com/saltstack/salty-vagrant/pull/98">pull request</a> for that, but it has not been merged yet.</p>

<p>So, save yourself a lot of hairpulling, fork the plugin, apply the pull request, and install the plugin from source.
After this, we’re getting close…</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:salt</span> <span class="k">do</span> <span class="o">|</span><span class="n">salt</span><span class="o">|</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">bootstrap_script</span> <span class="o">=</span> <span class="s1">'lib/salt-bootstrap/bootstrap-salt.sh'</span>

    <span class="n">salt</span><span class="p">.</span><span class="nf">install_master</span> <span class="o">=</span> <span class="kp">true</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">run_highstate</span> <span class="o">=</span> <span class="kp">true</span>

    <span class="n">salt</span><span class="p">.</span><span class="nf">minion_key</span> <span class="o">=</span> <span class="s1">'build/keys/nginx01.intranet.pem'</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">minion_pub</span> <span class="o">=</span> <span class="s1">'build/keys/nginx01.intranet.pub'</span>

    <span class="n">salt</span><span class="p">.</span><span class="nf">master_key</span> <span class="o">=</span> <span class="s1">'build/keys/master.pem'</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">master_pub</span> <span class="o">=</span> <span class="s1">'build/keys/master.pub'</span>

    <span class="n">salt</span><span class="p">.</span><span class="nf">seed_master</span> <span class="o">=</span> <span class="p">{</span>
        <span class="s1">'nginx01.intranet'</span> <span class="o">=&gt;</span> <span class="s1">'build/keys/nginx01.intranet.pub'</span>
    <span class="p">}</span>
<span class="k">end</span>

<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:nginx01</span> <span class="k">do</span> <span class="o">|</span><span class="n">node</span><span class="o">|</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">hostname</span> <span class="o">=</span> <span class="s1">'nginx01.intranet'</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">network</span> <span class="ss">:private_network</span><span class="p">,</span> <span class="ss">ip: </span><span class="s1">'10.1.14.100'</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">synced_folder</span> <span class="s1">'salt/roots/'</span><span class="p">,</span> <span class="s1">'/srv/'</span>
<span class="k">end</span></code></pre></figure>

<h2 id="where-is-my-master">Where is my master?</h2>

<p>By default, Salt minions look for a host called <code class="language-plaintext highlighter-rouge">salt</code>. Which of course cannot be found in the setup described above,
because the master is called <code class="language-plaintext highlighter-rouge">nginx01.intranet</code>. The easy solution would be to provide a custom minion configuration,
but I decided for a more future-proof solution: the <a href="https://github.com/smdahlen/vagrant-hostmanager">Hostmanager</a>.</p>

<p>This cute plugin updates the <code class="language-plaintext highlighter-rouge">/etc/hosts</code>-file on the guests and supports host aliases. It can also be used as a provisioner,
ensuring that all hosts are known to each other before the Salt provisioning starts. And it can also update the
<code class="language-plaintext highlighter-rouge">/etc/hosts</code>-file on the host machine, which is a nice feature to have.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">config</span><span class="p">.</span><span class="nf">hostmanager</span><span class="p">.</span><span class="nf">enabled</span> <span class="o">=</span> <span class="kp">false</span>             <span class="c1"># use explicit provisioning</span>
<span class="n">config</span><span class="p">.</span><span class="nf">hostmanager</span><span class="p">.</span><span class="nf">ignore_private_ip</span> <span class="o">=</span> <span class="kp">false</span>   <span class="c1"># use my :private_network IP</span>

<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:hostmanager</span>               <span class="c1"># provision the /etc/hosts file</span>
<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:salt</span> <span class="k">do</span> <span class="o">|...|</span>

<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:nginx01</span> <span class="k">do</span> <span class="o">|</span><span class="n">node</span><span class="o">|</span>
    <span class="c1"># ...</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">hostmanager</span><span class="p">.</span><span class="nf">aliases</span> <span class="o">=</span> <span class="sx">%w(salt salt.intranet)</span>   <span class="c1"># my aliases</span>
<span class="k">end</span></code></pre></figure>

<h2 id="not-so-fast">Not so fast…</h2>

<p>More fun ahead. For some idiotic reason, starting the Salt minion takes longer than starting the Salt master. Which
means that during a <code class="language-plaintext highlighter-rouge">vagrant up</code> provisioning run, the minion seems to be down when the master is trying to call its
highstate.</p>

<p>I tried all kinds of config tweaking to fix this, but in the end I gave up. I wanted to see some results.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:salt</span> <span class="k">do</span> <span class="o">|</span><span class="n">salt</span><span class="o">|</span>
    <span class="c1"># ...</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">run_highstate</span> <span class="o">=</span> <span class="kp">false</span>
<span class="k">end</span>

<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:nginx01</span> <span class="k">do</span> <span class="o">|</span><span class="n">node</span><span class="o">|</span>
    <span class="c1"># ...</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:shell</span><span class="p">,</span> <span class="ss">:inline</span> <span class="o">=&gt;</span> <span class="s1">'sleep 60; salt-call state.highstate'</span>
<span class="k">end</span></code></pre></figure>

<p>Did you notice the subtle <code class="language-plaintext highlighter-rouge">sleep 60</code> call? This <a href="http://en.wikipedia.org/wiki/Trial_and_error">scientifically determined</a> delay ensures that the
salt minion is up, running and connected when we finally do what we’ve always wanted to do: running the highstate.</p>

<p>Time for a <code class="language-plaintext highlighter-rouge">vagrant up</code>.</p>

<p>Mission Accomplished!</p>

<p>Well, almost…</p>

<h2 id="vps-deployment">VPS Deployment</h2>

<p>It’s fun to have a virtul infrastructure on your own computer, but my original goal has always been to deploy this to
<a href="https://www.digitalocean.com/?refcode=8d8ff680bec5">Digital Ocean</a> as well. And guess what: the setup described above does not work on a VPS.</p>

<p>Remember this line?</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">config</span><span class="p">.</span><span class="nf">hostmanager</span><span class="p">.</span><span class="nf">ignore_private_ip</span> <span class="o">=</span> <span class="kp">false</span>    <span class="c1"># use my :private_network IP</span></code></pre></figure>

<p>This line is necessary when working with the virtualbox provider, to ensure that the host files are seed with private
network IPs
instead of the well-known but useless <code class="language-plaintext highlighter-rouge">127.0.0.1</code> IP. But this setting is global, which means that my VPS will also
search for the <code class="language-plaintext highlighter-rouge">salt</code> host on <code class="language-plaintext highlighter-rouge">10.1.14.100</code>. Which is <a href="https://en.wikipedia.org/wiki/Private_network">not going to work</a>.</p>

<p>In theory, this can be overridden by using Vagrant’s provider override functionality:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provider</span> <span class="ss">:digital_ocean</span> <span class="k">do</span> <span class="o">|</span><span class="n">provider</span><span class="p">,</span> <span class="n">override</span><span class="o">|</span>
    <span class="c1"># ...</span>
    <span class="n">override</span><span class="p">.</span><span class="nf">hostmanager</span><span class="p">.</span><span class="nf">ignore_private_ip</span> <span class="o">=</span> <span class="kp">true</span>
<span class="k">end</span></code></pre></figure>

<p>But due to Vagrant’s arcane configuration inheritance settings, this nullifies my <code class="language-plaintext highlighter-rouge">node.hostmanager.aliases</code>
settings.</p>

<p>I tried to solve this by making the value of <code class="language-plaintext highlighter-rouge">ignore_private_ip</code> depend on Vagrant’s <code class="language-plaintext highlighter-rouge">current_provider</code> setting.
But that does not exist. <a href="https://github.com/mitchellh/vagrant/issues/1867">And it is not going to exist either.</a></p>

<p>As it turns out, the recommended approach is to define your own functions. The <code class="language-plaintext highlighter-rouge">Vagrantfile</code> is just a piece of
Ruby code, so as long as you can program Ruby, you can do everything you want. It’s just that I was never interested
in learning Ruby…</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nf">set_host_aliases</span><span class="p">(</span><span class="n">node</span><span class="p">,</span> <span class="n">aliases</span><span class="p">)</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">hostmanager</span><span class="p">.</span><span class="nf">aliases</span> <span class="o">=</span> <span class="n">aliases</span>
    <span class="n">node</span><span class="p">.</span><span class="nf">hostmanager</span><span class="p">.</span><span class="nf">ignore_private_ip</span> <span class="o">=</span> <span class="kp">false</span>

    <span class="n">node</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provider</span> <span class="ss">:digital_ocean</span> <span class="k">do</span> <span class="o">|</span><span class="n">provider</span><span class="p">,</span> <span class="n">override</span><span class="o">|</span>
        <span class="n">override</span><span class="p">.</span><span class="nf">hostmanager</span><span class="p">.</span><span class="nf">aliases</span> <span class="o">=</span> <span class="n">aliases</span>
        <span class="n">override</span><span class="p">.</span><span class="nf">hostmanager</span><span class="p">.</span><span class="nf">ignore_private_ip</span> <span class="o">=</span> <span class="kp">true</span>
    <span class="k">end</span>
<span class="k">end</span>

<span class="no">Vagrant</span><span class="p">.</span><span class="nf">configure</span><span class="p">(</span><span class="s2">"2"</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">config</span><span class="o">|</span>
    <span class="c1"># ...</span>
    <span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:nginx01</span> <span class="k">do</span> <span class="o">|</span><span class="n">node</span><span class="o">|</span>
        <span class="c1"># ...</span>
        <span class="n">set_host_aliases</span><span class="p">(</span><span class="n">node</span><span class="p">,</span> <span class="sx">%w(salt salt.intranet)</span><span class="p">)</span>
    <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p>If anyone has a better solution, please let me know! But despite my misgivings about this hack, <a href="http://nginx01.publysher.nl/">it works</a>.</p>

<p>Mission Accomplished! (for real now)</p>

<p><em>Don’t forget: my infra is a <a href="https://github.com/publysher/infra-example-nginx">repo</a>, so go ahead and fork it</em></p>]]></content><author><name></name></author><category term="devops" /><summary type="html"><![CDATA[How to provision a salt master on Digital Ocean.]]></summary></entry><entry><title type="html">Infra as a Repo: Using Git Submodules for the salt-vagrant-plugin</title><link href="https://www.publysher.nl/devops/2013/08/03/infra-as-repo-using-git-submodules-for.html" rel="alternate" type="text/html" title="Infra as a Repo: Using Git Submodules for the salt-vagrant-plugin" /><published>2013-08-03T00:00:00+00:00</published><updated>2013-08-03T00:00:00+00:00</updated><id>https://www.publysher.nl/devops/2013/08/03/infra-as-repo-using-git-submodules-for</id><content type="html" xml:base="https://www.publysher.nl/devops/2013/08/03/infra-as-repo-using-git-submodules-for.html"><![CDATA[<p>In my <a href="http://blog.publysher.nl/2013/07/infra-as-repo-using-vagrant-and-salt.html">previous post</a>, I set up a simple Nginx server using <a href="http://vagrantup.com/">Vagrant</a>, <a href="http://saltstack.com/">Salt Stack</a> and <a href="https://www.digitalocean.com/?refcode=8d8ff680bec5">Digital Ocean</a>.
However, there was a nagging issue with the <a href="https://github.com/saltstack/salty-vagrant">salt-vagrant-plugin</a> – I could not get it to install Salt correctly.
In this post, I am revisiting my Salt installation process.</p>

<p>From my previous post:</p>

<blockquote>
  <p>Also note that technically, the <code class="language-plaintext highlighter-rouge">vagrant-salt-plugin</code> is able to install Salt for you as well. However, for some
reason the plugin has decided that this requires a complete recompile of <code class="language-plaintext highlighter-rouge">python-zmq</code>, which I am not interested in.
So I use the official method of installing Salt before I start the plugin.</p>
</blockquote>

<p>This Shell provisioning annoyed me mightily, and I went out to investigate. As it turns out, the latest official
release of the <code class="language-plaintext highlighter-rouge">salt-vagrant-plugin</code> is still using version 1.5.2 of the
<a href="https://github.com/saltstack/salt-bootstrap">Salt-Boostrap script</a>, while the shell provisioning line uses the <a href="https://github.com/saltstack/salt-bootstrap/compare/v1.5.2...v1.5.5">much improved</a>, <a href="https://github.com/saltstack/salt-bootstrap/pull/159">highly praised</a>
and <a href="https://github.com/saltstack/salt-bootstrap/releases/tag/v1.5.5">vastly superior</a> 1.5.5 release.</p>

<p>Luckily, the <code class="language-plaintext highlighter-rouge">salt-vagrant-plugin</code> supports custom Salt bootstrap scripts using the aptly named <code class="language-plaintext highlighter-rouge">boostrap_script</code>
configuration parameter. Unfortunately, we can’t point it to e.g.
<a href="https://bootstrap.saltstack.org">https://bootstrap.saltstack.org</a>, but we must point it to a locally existing
file because…, er…, because <a href="http://bit.ly/14QGS6g">Ruby</a>.</p>

<p>So, all that remained now was a way to make sure my infra-as-a-repo project always contains a local copy of the
correct version of the bootstrap script. After some mucking about with <code class="language-plaintext highlighter-rouge">Makefile</code>s, <code class="language-plaintext highlighter-rouge">curl</code> and <code class="language-plaintext highlighter-rouge">wget</code>, this
eventually brought me to the long journey of understanding:</p>

<h2 id="git-submodules">Git Submodules</h2>

<p><a href="http://git-scm.com/book/en/Git-Tools-Submodules">Git Submodules</a>. As it turned out, this was a surprisingly short journey. Writing this post took more time than
understanding submodules. Git submodules allow you to add a live link to a fixed version of a 3rd part dependency in
another git repository.</p>

<figure class="highlight"><pre><code class="language-bash" data-lang="bash"><span class="c"># Create a directory for your 3rd-party dependencies</span>
<span class="nb">mkdir </span>lib
<span class="c"># Include the dependency</span>
git submodule add git@github.com:saltstack/salt-bootstrap.git lib/salt-bootstrap
<span class="c"># Pin the dependency</span>
<span class="nb">cd </span>lib/salt-bootstrap
git checkout v1.5.5</code></pre></figure>

<p>And that’s it. I changed my Salt provisioning block in the Vagrant file to this:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:salt</span> <span class="k">do</span> <span class="o">|</span><span class="n">salt</span><span class="o">|</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">minion_config</span> <span class="o">=</span> <span class="s1">'salt/standalone-minion'</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">bootstrap_script</span> <span class="o">=</span> <span class="s1">'lib/salt-bootstrap/bootstrap-salt.sh'</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">run_highstate</span> <span class="o">=</span> <span class="kp">true</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">verbose</span> <span class="o">=</span> <span class="kp">true</span>
<span class="k">end</span></code></pre></figure>

<p>and <a href="http://translate.google.com/#fr/en/Voil%C3%A0!">voilà!</a>, I could remove the entire Shell provisioning line.</p>

<p>Mission Accomplished!</p>

<h2 id="so-what">So what?</h2>

<p>This exercise has brought me three things. First of all, I now understand git submodules. Try it yourself. It’s nice.</p>

<p>Second, the separate shell provisioning step really bugged me. I no longer have to roam the streets at 2AM, moaning
about this annoying hack.</p>

<p>And finally, the <code class="language-plaintext highlighter-rouge">salt-vagrant-plugin</code> is actually quite smart; my happy shell hack reprovisioned Salt Stack at every
run, while the plugin does some nifty detection stuff. This has improved the speed of reprovisioning. Which is nice
when you’re doing this in your spare time and need to
reprovision a lot.</p>

<h2 id="git">Git</h2>

<p>Of course, the exact commit at the time of writing has been preserved in my repository. Go ahead and
<a href="https://github.com/publysher/infra-example-nginx/tree/v1.1">fork my repo on Github</a>.</p>]]></content><author><name></name></author><category term="devops" /><summary type="html"><![CDATA[Using git submodules to reuse other people's code]]></summary></entry><entry><title type="html">Infra as a Repo: Using Vagrant and Salt Stack to deploy Nginx on DigitalOcean</title><link href="https://www.publysher.nl/devops/2013/07/28/infra-as-repo-using-vagrant-and-salt.html" rel="alternate" type="text/html" title="Infra as a Repo: Using Vagrant and Salt Stack to deploy Nginx on DigitalOcean" /><published>2013-07-28T00:00:00+00:00</published><updated>2013-07-28T00:00:00+00:00</updated><id>https://www.publysher.nl/devops/2013/07/28/infra-as-repo-using-vagrant-and-salt</id><content type="html" xml:base="https://www.publysher.nl/devops/2013/07/28/infra-as-repo-using-vagrant-and-salt.html"><![CDATA[<p>I believe that managing your infrastructure can and should be fun. Recently I have been toying around with
<a href="http://vagrantup.com">Vagrant</a> and <a href="http://saltstack.com/">Salt Stack</a> to make this a reality. This weekend, 
I managed to combine these tools to automatically provision a new Nginx server on 
<a href="https://www.digitalocean.com/?refcode=8d8ff680bec5">Digital Ocean</a>.</p>

<p>This in itself is nothing new - the interesting part is where I have published the entire script as a Github 
repository without sacrificing any security.</p>

<p>If you’re not interested in the story and just want to go and reproduce my infrastructure, go ahead and 
<a href="https://github.com/publysher/infra-example-nginx/tree/v1.0">fork my repo on Github</a>.</p>

<h2 id="the-base-vagrantfile">The base Vagrantfile</h2>

<p>I began by using <a href="http://vagrantup.com">Vagrant</a>, an exciting tool that abstracts away all VM hassles into a single 
configuration file. Using a VirtualBox image I created earlier using <a href="https://github.com/jedi4ever/veewee">Veewee</a>, 
the following Vagrantfile allowed me to spin up and destroy a local Debian Wheezy VM.</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="no">Vagrant</span><span class="p">.</span><span class="nf">configure</span><span class="p">(</span><span class="s2">"2"</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">config</span><span class="o">|</span>

  <span class="c1"># Default configuration for Virtualbox</span>
  <span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">box</span> <span class="o">=</span> <span class="s1">'debian-wheezy-64'</span>
  <span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">box_url</span> <span class="o">=</span> <span class="s1">'https://www.dropbox.com/s/00ndb5ea4k8hyoy/debian-wheezy-64.box'</span>

  <span class="c1"># Name the VM</span>
  <span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">define</span> <span class="ss">:nginx01</span>

<span class="k">end</span></code></pre></figure>

<p>Just by having this simple file, I can now manage a VM with the commands <code class="language-plaintext highlighter-rouge">vagrant up</code>, 
<code class="language-plaintext highlighter-rouge">vagrant ssh</code> and <code class="language-plaintext highlighter-rouge">vagrant destroy</code>.</p>

<h2 id="salting-the-image">Salting the image</h2>

<p>Starting a VM like this is already a sweet experience, but it gets better. The
<a href="https://github.com/saltstack/salty-vagrant">salty-vagrant</a> plugin allows me to automatically install and configure
software on the VM using the super sweet Salt Stack framework.</p>

<p>Yes, I know, Vagrant supports Puppet and Chef provisioning out of the box, but some time ago I decided that I don’t
just want provisioning for my infrastructure. I want a remote execution framework as well. And that’s how you end up
with Salt Stack.</p>

<p>Anyway, the following lines in my Vagrantfile were enough to enable Salt Stack:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># Mount salt roots, so we can do masterless setup</span>
<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">synced_folder</span> <span class="s1">'salt/roots/'</span><span class="p">,</span> <span class="s1">'/srv/'</span>

<span class="c1"># Forward 8080 to nginx</span>
<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">network</span> <span class="ss">:forwarded_port</span><span class="p">,</span> <span class="ss">guest: </span><span class="mi">80</span><span class="p">,</span> <span class="ss">host: </span><span class="mi">8080</span>

<span class="c1"># Provisioning #1: install salt stack</span>
<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:shell</span><span class="p">,</span>
    <span class="ss">:inline</span> <span class="o">=&gt;</span> <span class="s1">'wget -O - http://bootstrap.saltstack.org | sudo sh'</span>

<span class="c1"># Provisioning #2: masterless highstate call</span>
<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provision</span> <span class="ss">:salt</span> <span class="k">do</span> <span class="o">|</span><span class="n">salt</span><span class="o">|</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">minion_config</span> <span class="o">=</span> <span class="s1">'salt/minion'</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">run_highstate</span> <span class="o">=</span> <span class="kp">true</span>
    <span class="n">salt</span><span class="p">.</span><span class="nf">verbose</span> <span class="o">=</span> <span class="kp">true</span>
<span class="k">end</span></code></pre></figure>

<p>This, and some Salt files of course. They can be found in my
<a href="https://github.com/publysher/infra-example-nginx/tree/v1.0">Github repo</a> under <code class="language-plaintext highlighter-rouge">salt/roots</code>. In this case,
the Salt files just install and configure a simple Nginx server, but it’s the principle that counts.</p>

<p>Also note that technically, the <code class="language-plaintext highlighter-rouge">vagrant-salt-plugin</code> is able to install Salt for you as well. However, for some
reason the plugin has decided that this requires a complete recompile of <code class="language-plaintext highlighter-rouge">python-zmq</code>, which I am not interested in.
So I use the official method of installing Salt before I start the plugin.</p>

<p>And now, after doing a <code class="language-plaintext highlighter-rouge">vagrant up</code>, the VM is automatically provisioned with a running Nginx server, accessible
through <a href="http://localhost:8080">http://localhost:8080</a>.</p>

<h2 id="adding-digital-ocean">Adding Digital Ocean</h2>

<p>Once again a sweet experience, but hosting my infrastructure on my development machine is not really future-proof.
Which brings me to the next part: deploying the exact same configuration on a real VPS.</p>

<p>Given [the current list of available Vagrant plugins]
(https://github.com/mitchellh/vagrant/wiki/Available-Vagrant-Plugins), and the fact that I don’t want to spend too much
on this right now, I decided on using <a href="https://www.digitalocean.com/?refcode=8d8ff680bec5">Digital Ocean</a>. They offer
nice small SSD-backed VPSs for only $5,- a month. And you pay by the hour. Which means that this entire exercise has
cost me $0.05 so far.</p>

<p>The README of the <a href="https://github.com/smdahlen/vagrant-digitalocean">vagrant-digitalocean</a> plugin is self-explanatory,
but it has one major flaw: it puts your client ID and API key in the main Vagrantfile. Call me old-fashioned, but I
don’t like sharing this information on Github.</p>

<p>Luckily, Vagrant has <a href="http://docs.vagrantup.com/v2/vagrantfile/index.html">a complete settings-merging process</a> in
place, which meant I could simply create the following <code class="language-plaintext highlighter-rouge">~/.vagrant.d/Vagrantfile</code>:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="no">Vagrant</span><span class="p">.</span><span class="nf">configure</span><span class="p">(</span><span class="s2">"2"</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">config</span><span class="o">|</span>
    <span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provider</span> <span class="ss">:digital_ocean</span> <span class="k">do</span> <span class="o">|</span><span class="n">provider</span><span class="p">,</span> <span class="n">override</span><span class="o">|</span>
        <span class="n">override</span><span class="p">.</span><span class="nf">ssh</span><span class="p">.</span><span class="nf">private_key_path</span> <span class="o">=</span> <span class="s1">'~/.ssh/id_dsa'</span>
        <span class="n">override</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">box_url</span> <span class="o">=</span> <span class="s1">'https://github.com/smdahlen/vagrant-digitalocean/raw/master/box/digital_ocean.box'</span>

        <span class="n">provider</span><span class="p">.</span><span class="nf">client_id</span> <span class="o">=</span> <span class="s1">'MY-SECRET-ID'</span>
        <span class="n">provider</span><span class="p">.</span><span class="nf">api_key</span> <span class="o">=</span> <span class="s1">'MY-SUPER-SECRET-API-KEY'</span>
    <span class="k">end</span>
<span class="k">end</span></code></pre></figure>

<p>Note the <code class="language-plaintext highlighter-rouge">override.vm.box_url</code> setting – my beautiful preinstalled Wheezy VM is useless on Digital Ocean, so I just use
their dummy box. Always.</p>

<p>Having set up my private information, I just needed to add the following lines to my main Vagrantfile:</p>

<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># VM-specific digital ocean config</span>
<span class="n">config</span><span class="p">.</span><span class="nf">vm</span><span class="p">.</span><span class="nf">provider</span> <span class="ss">:digital_ocean</span> <span class="k">do</span> <span class="o">|</span><span class="n">provider</span><span class="o">|</span>
    <span class="n">provider</span><span class="p">.</span><span class="nf">image</span> <span class="o">=</span> <span class="s1">'Debian 7.0 x64'</span>
    <span class="n">provider</span><span class="p">.</span><span class="nf">region</span> <span class="o">=</span> <span class="s1">'New York 1'</span>
    <span class="n">provider</span><span class="p">.</span><span class="nf">size</span> <span class="o">=</span> <span class="s1">'512MB'</span>
<span class="k">end</span></code></pre></figure>

<h2 id="deploying-the-image">Deploying the image</h2>

<p>The proof is in the pudding (apparently), so with great trepidation I did a <code class="language-plaintext highlighter-rouge">vagrant up --provider digital_ocean</code>.</p>

<p>You should try it yourself – this was really quite exciting. Just a few minutes later, I could access my professionally
provisioned Nginx VPS on <a href="http://192.241.146.220">http://192.241.146.220</a>. Without me ever SSH-ing to the server itself.</p>

<p>Mission Accomplished!</p>

<p>Or was it?</p>

<h2 id="managing-the-deployed-image">Managing the deployed image</h2>

<p>At the moment, Vagrant does not support multiple providers at the same time. So in order to start a local VM
(<code class="language-plaintext highlighter-rouge">vagrant up</code>), you should do a <code class="language-plaintext highlighter-rouge">vagrant destroy</code> on the current provider first.</p>

<p>This is not good. The <code class="language-plaintext highlighter-rouge">vagrant destroy</code> command does exactly what it says, and it destroys your VPS.
Which is sort of missing the point.</p>

<p>In order to switch back to local development, you should remove the <code class="language-plaintext highlighter-rouge">.vagrant/machines/$NAME/digital_ocean/id</code> file.
This makes Vagrant forget everything it knows about your VPS and <code class="language-plaintext highlighter-rouge">vagrant up</code> will start a local VM as expected.</p>

<p>And now for the nice part: the <code class="language-plaintext highlighter-rouge">vagrant-digitalocean</code> plugin actually does not care about this.
The next time you do a <code class="language-plaintext highlighter-rouge">vagrant up --provider digital_ocean</code>, it will detect your existing VPS by name, and
automatically reinstate the <code class="language-plaintext highlighter-rouge">id</code>-file.</p>

<h2 id="reprovisioning-the-image">Reprovisioning the image</h2>

<p>Provisioning a server is nice, but being able to reprovision a running server is even better. There are three ways to
do this.</p>

<p>The first one is <code class="language-plaintext highlighter-rouge">vagrant provision</code>, which just runs the provisioning scripts again. This is great for incremental
updates, and it keeps your server online, but it does not guarantee that provisioning works from an initial state as
well.</p>

<p>The second one is <code class="language-plaintext highlighter-rouge">vagrant destroy ; vagrant up --provider digital_ocean</code>. This will recreate your VPS from the ground
up, ensuring a future-proof provisioning. Unfortunately, Digital Ocean does not guarantee that this will give you the
same IP address. You will also occur a few minutes of downtime.</p>

<p>The final one is <code class="language-plaintext highlighter-rouge">vagrant rebuild</code>, which does guarantee the same IP address and seems to be functionally equivalent
to the previous method. This too gives you a few minutes of downtime.</p>

<h2 id="one-server-does-not-an-infrastructure-make">One server does not an infrastructure make</h2>

<p>All of this has of course merely touched the surface of real infrastructure provisioning. Because I don’t let Digital
Ocean manage my DNS, I have to manually update my records, the server does not do any monitoring, the current
configuration is not really exciting, and using a masterless Salt minion setup sort of defeats the purpose of using
Salt.</p>

<p>So what.</p>

<p>This exercise has shown me that having your infra as a repo is a viable position, and I am determined to continue down
this path. It might even result in another blog post.</p>]]></content><author><name></name></author><category term="devops" /><summary type="html"><![CDATA[Provisioning an Nginx server on DigitalOcean using Vagrant and SaltStack]]></summary></entry><entry><title type="html">Using RDF to populate ZooWizard, a case study</title><link href="https://www.publysher.nl/python/2012/08/19/using-rdf-to-populate-zoowizard-case.html" rel="alternate" type="text/html" title="Using RDF to populate ZooWizard, a case study" /><published>2012-08-19T00:00:00+00:00</published><updated>2012-08-19T00:00:00+00:00</updated><id>https://www.publysher.nl/python/2012/08/19/using-rdf-to-populate-zoowizard-case</id><content type="html" xml:base="https://www.publysher.nl/python/2012/08/19/using-rdf-to-populate-zoowizard-case.html"><![CDATA[<p>For some time, I’ve been keeping a small website called <a href="http://www.zoowizard.eu/">ZooWizard</a>. It’s main purpose: to
have an outlet for two of my main hobbies: visiting zoos and programming.</p>

<p>One of the problems with keeping this website up to date is the secondary data, i.e. data about zoos and animals.
Until now, this data has been sourced using Wikipedia, personal experience and of course: lot’s of manual data entry.</p>

<p>This was nice for a while because it’s a great way to get started, but for some time this manual aspect has been
getting on my nerves. So, I decided to explore the possibilities of <a href="http://linkeddata.org/">Linked Data</a>.
This blog post is the first part in this case study: creating an information-rich collection of European zoos.</p>

<p>The code to create this collection can be found in my GitHub repository
<a href="https://github.com/publysher/zoowizard-rdf">zoowizard-rdf</a>. If you want to replicate what I’ve done,
please refer to the <a href="https://github.com/publysher/zoowizard-rdf/tags">tag v1</a>.</p>

<p>All the code has been written in Python 2.7 and it uses the following libraries:</p>

<ul>
  <li><a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/">BeautifulSoup</a> for parsing HTML</li>
  <li><a href="http://rdflib.readthedocs.org/en/latest/index.html">RDFLib</a> for managing RDF</li>
</ul>

<h2 id="finding-a-starting-point">Finding a starting point</h2>

<p>One of my favorite references for obtaining information about zoos so far has been the
<a href="http://www.zoochat.com/">ZooChat</a> website which contains
an
<a href="http://www.zoochat.com/zoos/">exhaustive list of all the zoos around the world</a>.
It’s more complete than Wikipedia, so I’ve decided to start here.</p>

<p>Of course, the first problem that arises here is the fact that ZooChat contains <em>no linked data whatsoever</em>.  So,
I decided to start out by creating a dataset based on their zoo list. Since web scraping is a dirty hobby,
I won’t go into too much details. Suffice it to say that the first step was a small program called <code class="language-plaintext highlighter-rouge">zoochat2py</code> which
scrapes the data into a pickled list of dictionaries like this:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="p">{</span> <span class="sh">'</span><span class="s">zoochat_id</span><span class="sh">'</span><span class="p">:</span> <span class="sa">u</span><span class="sh">'</span><span class="s">43</span><span class="sh">'</span><span class="p">,</span>
  <span class="sh">'</span><span class="s">name</span><span class="sh">'</span><span class="p">:</span> <span class="sa">u</span><span class="sh">'</span><span class="s">Artis Royal Zoo</span><span class="sh">'</span><span class="p">,</span>
  <span class="sh">'</span><span class="s">alternative_names</span><span class="sh">'</span><span class="p">:</span> <span class="p">[</span><span class="sa">u</span><span class="sh">'</span><span class="s">Artis Zoo</span><span class="sh">'</span><span class="p">,</span> <span class="sa">u</span><span class="sh">'</span><span class="s">Amsterdam Zoo</span><span class="sh">'</span><span class="p">,</span> <span class="sa">u</span><span class="sh">'</span><span class="s">Natura Artis Magistra</span><span class="sh">'</span><span class="p">],</span>
  <span class="sh">'</span><span class="s">country</span><span class="sh">'</span><span class="p">:</span> <span class="sa">u</span><span class="sh">'</span><span class="s">Netherlands</span><span class="sh">'</span><span class="p">,</span>
  <span class="sh">'</span><span class="s">website</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">http://www.artis.nl/en/artis-royal-zoo/</span><span class="sh">'</span><span class="p">,</span>
  <span class="sh">'</span><span class="s">wikipedia</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">http://en.wikipedia.org/wiki/Artis_Magistra_zoo</span><span class="sh">'</span><span class="p">,</span>
  <span class="sh">'</span><span class="s">facebook</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">http://www.facebook.com/Artis</span><span class="sh">'</span><span class="p">,</span>
  <span class="sh">'</span><span class="s">twitter</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">http://twitter.com/artis</span><span class="sh">'</span><span class="p">,</span>
  <span class="sh">'</span><span class="s">map</span><span class="sh">'</span><span class="p">:</span> <span class="sh">'</span><span class="s">http://www.zoochat.com/maps/artis-zoo</span><span class="sh">'</span><span class="p">,</span>
<span class="p">}</span></code></pre></figure>

<h2 id="creating-an-rdf-dataset">Creating an RDF Dataset</h2>

<p>The next step was to create an RDF dataset based on this information. I quickly found out that creating an RDF
dataset is not trivial, and I decided first to read the
<a href="http://linkeddatabook.com/editions/1.0">Linked Data book</a> and follow their advice. Go, read the book. It’s really good.</p>

<h3 id="determining-cool-uris">Determining cool URI’s</h3>

<p>The first step to consider is the Naming Scheme. Using <a href="http://zoowizard.eu">http://zoowizard.eu</a> as my basic namespace seemed like a
logical choice and I settled on using <a href="http://zoowizard.eu/datasource/zoochat">http://zoowizard.eu/datasource/zoochat</a> as the URI for the dataset itself,
and <a href="http://zoowizard.eu/datasource/zoochat/NUMBER">http://zoowizard.eu/datasource/zoochat/NUMBER</a> as the format for URIs for the individual zoos. This leaves me
free to add other third-party datasets in the future, and it won’t pollute the rest of my namespace.</p>

<p>I briefly toyed with the idea to use hash-based URIs for the individual zoos, but when it turned out I needed some
kind of sub-URI’s for the social references, I immediately went back to the previous scheme.</p>

<h3 id="finding-the-right-vocabulary">Finding the right vocabulary</h3>

<p>This turned out to be the hardest part of the whole exercise. I had already decided that this small dataset should
not require a new vocabulary. But how do you find the correct vocabulary for what you want to express?</p>

<p>In the end, I spent some time looking at published RDF resources such as
<a href="http://dbpedia.org/About">DBpedia</a> and the
<a href="http://dbpedia.org/About">BBC Wildlife Finder</a> and
slowly built up a list of relevant namespaces.</p>

<p>The most important ones are of course the original RDF and RDF Schema namespaces. Due to previous experience with
Schema.org in HTML5 I decided to include the Schema namespace as well. So I quickly ended up with:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;http://zoowizard.eu/datasource/zoochat/43&gt; a schema:Zoo,
    rdfs:label "Artis Royal Zoo";
    schema:addressCountry "Netherlands";
    schema:map &lt;http://www.zoochat.com/maps/artis-zoo&gt;;
    schema:name "Artis Royal Zoo" .
</code></pre></div></div>

<p>A nice first step, but this was only part of the information at my disposal. So, I turned to the
<a href="http://xmlns.com/foaf/spec/#">FOAF vocabulary</a> to represent the links to various websites.
This is where I discovered that I needed to have separate URI’s for the Facebook and Twitter links, because FOAF
uses a separate Class to represent an account. I decided to use the #facebook and #twitter extensions for the existing
names, resulting in the following representation:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;http://zoowizard.eu/datasource/zoochat/43&gt; a schema:Zoo,
        foaf:Organization;
    # ...
    foaf:account &lt;http://zoowizard.eu/datasource/zoochat/43#facebook&gt;,
        &lt;http://zoowizard.eu/datasource/zoochat/43#twitter&gt;;
    foaf:based_near "Netherlands";
    foaf:homepage &lt;http://www.artis.nl/en/artis-royal-zoo/&gt;;
    foaf:isPrimaryTopicOf &lt;http://en.wikipedia.org/wiki/Artis_Magistra_zoo&gt; .

&lt;http://zoowizard.eu/datasource/zoochat/43#facebook&gt; a foaf:OnlineAccount;
    foaf:accountProfilePage &lt;http://www.facebook.com/Artis&gt;;
    foaf:accountServiceHomePage &lt;http://www.facebook.com&gt; .

&lt;http://zoowizard.eu/datasource/zoochat/43#twitter&gt; a foaf:OnlineAccount;
    foaf:accountProfilePage &lt;http://twitter.com/artis&gt;;
    foaf:accountServiceHomePage &lt;http://www.twitter.com&gt; .
</code></pre></div></div>

<p>Yes, I cheated a bit. <code class="language-plaintext highlighter-rouge">foaf:accountProfilePage</code> is not a documented property but it seemed like the best way to denote
Facebook pages.</p>

<p>With this, I only needed to add skos:label and skos:prefLabel triples to represent all the available information as
RDF triples. And I ended up with this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; .
@prefix foaf: &lt;http://xmlns.com/foaf/0.1/&gt; .
@prefix schema: &lt;http://schema.org/&gt; .
@prefix skos: &lt;http://www.w3.org/2004/02/skos/core#&gt; .

&lt;http://zoowizard.eu/datasource/zoochat/43&gt; a schema:Zoo,
        foaf:Organization;
    rdfs:label "Artis Royal Zoo";
    schema:addressCountry "Netherlands";
    schema:map &lt;http://www.zoochat.com/maps/artis-zoo&gt;;
    schema:name "Artis Royal Zoo";
    skos:altLabel "Amsterdam Zoo",
        "Artis Zoo",
        "Natura Artis Magistra";
    skos:prefLabel "Artis Royal Zoo";
    foaf:account &lt;http://zoowizard.eu/datasource/zoochat/43#facebook&gt;,
        &lt;http://zoowizard.eu/datasource/zoochat/43#twitter&gt;;
    foaf:based_near "Netherlands";
    foaf:homepage &lt;http://www.artis.nl/en/artis-royal-zoo/&gt;;
    foaf:isPrimaryTopicOf &lt;http://en.wikipedia.org/wiki/Artis_Magistra_zoo&gt;,
        &lt;http://zoowizard.eu/datasource/zoochat/43.rdf&gt; .

&lt;http://zoowizard.eu/datasource/zoochat/43#facebook&gt; a foaf:OnlineAccount;
    foaf:accountProfilePage &lt;http://www.facebook.com/Artis&gt;;
    foaf:accountServiceHomePage &lt;http://www.facebook.com&gt; .

&lt;http://zoowizard.eu/datasource/zoochat/43#twitter&gt; a foaf:OnlineAccount;
    foaf:accountProfilePage &lt;http://twitter.com/artis&gt;;
    foaf:accountServiceHomePage &lt;http://www.twitter.com&gt; .
</code></pre></div></div>

<h2 id="publishing-my-rdf">Publishing my RDF</h2>

<p>Now it was time to convert this graph consisting of 19,586 triples to something that could be served over the internet.
And once again, I turned to the Linked Data book to see what they suggest.</p>

<p>After reading the book again, I decided to describe the dataset itself using the Dublin Core and VoID vocabularies,
to use the 303 approach to keep concepts and descriptions apart, to create a separate XML file for each zoo and the
dataset, and to create an NT file containing the entire dump.</p>

<h3 id="describing-the-dataset">Describing the dataset</h3>

<p>This was quite easy, and for now I ended up with:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@prefix dc: &lt;http://purl.org/dc/terms/&gt; .
@prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; .
@prefix void: &lt;http://rdfs.org/ns/void#&gt; .

&lt;http://zoowizard.eu/datasource/zoochat&gt; a void:Dataset;
    rdfs:label "List of All Zoos Worldwide";
    dc:description "RDF description extracted from http://www.zoochat.com/zoos";
    dc:license &lt;http://creativecommons.org/licenses/by-sa/3.0/&gt;;
    dc:modified "2012-08-19"^^&lt;http://www.w3.org/2001/XMLSchema#date&gt;;
    dc:source &lt;http://www.zoochat.com/zoos&gt;;
    dc:title "List of All Zoos Worldwide";
    void:dataDump &lt;http://zoowizard.eu/datasource/zoochat/all.nt&gt;;
    void:exampleResource &lt;http://zoowizard.eu/datasource/zoochat/43&gt;;
    void:feature &lt;http://www.w3.org/ns/formats/RDF_XML&gt; .
</code></pre></div></div>

<p>Followed by a lot of entries like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;http://zoowizard.eu/datasource/zoochat/43&gt; void:inDataset
    &lt;http://zoowizard.eu/datasource/zoochat&gt; .
</code></pre></div></div>

<h3 id="using-the-303-approach">Using the 303-approach</h3>

<p>The 303-approach basically states that things and descriptions should be kept separated. The Linked Data book
suggests to use a different URI for the description and to relate the description and the thing by using
foaf:primaryTopic links. I decided to give my descriptions an .rdf extension, and using the power of RDFLib I could
easily extend the graph:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="n">items</span> <span class="o">=</span> <span class="n">itertools</span><span class="p">.</span><span class="nf">chain</span><span class="p">(</span><span class="n">g</span><span class="p">.</span><span class="nf">subjects</span><span class="p">(</span><span class="n">RDF</span><span class="p">.</span><span class="nb">type</span><span class="p">,</span> <span class="n">SCHEMA</span><span class="p">.</span><span class="n">Zoo</span><span class="p">),</span>
                        <span class="n">g</span><span class="p">.</span><span class="nf">subjects</span><span class="p">(</span><span class="n">RDF</span><span class="p">.</span><span class="nb">type</span><span class="p">,</span> <span class="n">VOID</span><span class="p">.</span><span class="n">Dataset</span><span class="p">))</span>

<span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">items</span><span class="p">:</span>
    <span class="n">document</span> <span class="o">=</span> <span class="n">item</span> <span class="o">+</span> <span class="sh">'</span><span class="s">.rdf</span><span class="sh">'</span>
    <span class="n">g</span><span class="p">.</span><span class="nf">add</span><span class="p">((</span><span class="n">item</span><span class="p">,</span> <span class="n">FOAF</span><span class="p">.</span><span class="n">isPrimaryTopicOf</span><span class="p">,</span> <span class="nc">URIRef</span><span class="p">(</span><span class="n">document</span><span class="p">)))</span>
    <span class="n">g</span><span class="p">.</span><span class="nf">add</span><span class="p">((</span><span class="nc">URIRef</span><span class="p">(</span><span class="n">document</span><span class="p">),</span> <span class="n">FOAF</span><span class="p">.</span><span class="n">primaryTopic</span><span class="p">,</span> <span class="n">item</span><span class="p">))</span></code></pre></figure>

<h3 id="creating-the-files">Creating the files</h3>

<p>Actually creating the files turned out to be the easiest of all, once again thanks to RDFLib. It’s serialization 
feature makes it a breeze to create RDF/XML files or NT files. Or even N3 output such as used in this post.</p>

<p>The biggest trick was to create a relevant subgraph. So far, I’ve come up with this:</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">create_subgraph</span><span class="p">(</span><span class="n">graph</span><span class="p">,</span> <span class="n">item</span><span class="p">):</span>
    <span class="n">g</span> <span class="o">=</span> <span class="n">rdflib</span><span class="p">.</span><span class="nc">Graph</span><span class="p">()</span>
    <span class="n">namespaces</span><span class="p">.</span><span class="nf">init_bindings</span><span class="p">(</span><span class="n">g</span><span class="p">)</span>

    <span class="k">for</span> <span class="n">triple</span> <span class="ow">in</span> <span class="n">graph</span><span class="p">.</span><span class="nf">triples</span><span class="p">((</span><span class="n">item</span><span class="p">,</span> <span class="bp">None</span><span class="p">,</span> <span class="bp">None</span><span class="p">)):</span>
        <span class="n">g</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="n">triple</span><span class="p">)</span>

    <span class="k">for</span> <span class="n">triple</span> <span class="ow">in</span> <span class="n">graph</span><span class="p">.</span><span class="nf">triples</span><span class="p">((</span><span class="bp">None</span><span class="p">,</span> <span class="bp">None</span><span class="p">,</span> <span class="n">item</span><span class="p">)):</span>
        <span class="n">g</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="n">triple</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">g</span></code></pre></figure>

<p>This takes care of collecting all the triples in which the required URI is either the subject or the object. It could
require a bit more transitivity, and RDFLib seems to have good utilities for that,
but it was a nice exercise nevertheless.</p>

<h2 id="serving-the-files">Serving the files</h2>

<p>The last step was to upload my documents to my web server and to configure Apache to use the 303 approach. Given the
lack of complexity for this dataset, I used the following rules in my config:</p>

<figure class="highlight"><pre><code class="language-apache" data-lang="apache"><span class="nc">RewriteEngine</span> <span class="ss">on</span>
<span class="nc">AddType</span> application/rdf+xml;charset=UTF-8 .rdf

<span class="nc">RewriteRule</span> ^/datasource/zoochat$ http://zoowizard.eu/datasource/zoochat.rdf [redirect=303]
<span class="nc">RewriteRule</span> ^/datasource/zoochat/(\d+)$ http://zoowizard.eu/datasource/zoochat/$1.rdf [redirect=303]</code></pre></figure>

<p>This approach won’t work as my datasets grow, but for now it suffices.</p>

<h2 id="whats-next">What’s next?</h2>

<p>So far, I’ve succeeded in creating a good RDF representation containing a list of all the zoos worldwide. There are
several next steps which I plan to undertake. They include, but are not limited to:</p>

<ul>
  <li>Creating my own authoritive dataset based on this external dataset</li>
  <li>Linking this dataset to DBpedia</li>
  <li>Linking this dataset to Geonames</li>
  <li>Dynamically serving this dataset</li>
  <li>Generating HTML pages from this dataset</li>
  <li>etc.</li>
</ul>]]></content><author><name></name></author><category term="python" /><summary type="html"><![CDATA[For some time, I’ve been keeping a small website called ZooWizard. It’s main purpose: to have an outlet for two of my main hobbies: visiting zoos and programming.]]></summary></entry><entry><title type="html">Stencyl Tower Defense Tutorial: Do the Wave</title><link href="https://www.publysher.nl/game/2012/08/04/stencyl-tower-defense-10-do-wave.html" rel="alternate" type="text/html" title="Stencyl Tower Defense Tutorial: Do the Wave" /><published>2012-08-04T00:00:00+00:00</published><updated>2012-08-04T00:00:00+00:00</updated><id>https://www.publysher.nl/game/2012/08/04/stencyl-tower-defense-10-do-wave</id><content type="html" xml:base="https://www.publysher.nl/game/2012/08/04/stencyl-tower-defense-10-do-wave.html"><![CDATA[<p>Last week I talked explained how to lose. This week, I’ll talk about winning. After a short introduction on what it
means to win a Tower Defense level, the tutorial will explain how to have multiple waves and how to recognize that
the player has won.</p>

<p><a href="http://www.stencyl.com/game/play/13985">The result of this part can be seen here</a>; you can also find it on
StencylForge under the name “Publysher – TD Tutorial part #10”.</p>

<h2 id="winning-what-does-it-mean">Winning: What does it mean?</h2>

<p>In a typical tower defense game you win the level when you have survived all waves; in other words: when all waves
have passed and you have at least one life left.</p>

<p>This of course begs the question: what does it mean for a wave to have passed? In our current game,
a wave has passed when every enemy that has been spawned by this wave has left the screen – either by being killed or
by passing the finish line.</p>

<p>So in order to implement winning in our Tower Defense game, we need to do the following:</p>

<ul>
  <li>Detect when a wave has passed</li>
  <li>Detect when all the waves have passed and start the “player won level” feedback.</li>
</ul>

<p>For now, the feedback will consist of a happy “You Won” message, after which the level will start again.</p>

<h2 id="multiple-waves">Multiple Waves</h2>

<p>A closely related aspect is the concept of multiple waves. Right now, our Tower Defense game supports only one single wave – however, once a wave has been exhausted a new wave ought to arrive. This new wave should start after a predetermined time, and the player should have the possibility to call it early.</p>

<p>In order to have a game with multiple waves, we need the following:</p>

<ul>
  <li>Detect when a wave has passed</li>
  <li>Start a new wave after the previous wave has passed</li>
  <li>Show how many waves there are left</li>
  <li>Show a button to call the next wave early</li>
</ul>

<p>Notice how the first requirement is identical to the first requirement of winning the game!</p>

<h2 id="structure">Structure</h2>

<p>Let’s start with showing the number of waves. Each Tower defense game has its own method of doing this,
but for this game we’ll keep it simple: just an icon with two numbers: the current wave and the total number of waves.
If this sounds familiar, it should be – it is going to be very similar to the Number of Lives Manager and the Score
Manager. When a wave is exhausted, a button will show up somewhere on the screen. Clicking this button will cause the
next wave to appear; if a certain amount of time has elapsed and the player hasn’t clicked the button,
the next wave will appear anyway.</p>

<p>In order to implement this, I will create a few actors, two new behaviors and I will extend a number of existing
behaviors. The diagram below gives an overview of the various new and modified components:</p>

<p><img src="/images/stencyl/step10-1.png" alt="" /></p>

<h2 id="intermezzo-uml">Intermezzo: UML</h2>

<p>Quite a complicated diagram, isn’t it? By the way, this kind of drawing is called an UML diagram,
and it is a great way to visualize the different components in your game and to track the interactions between them.</p>

<p>To read a diagram like this, start at the top where I have drawn the our Test Level. For this part of the tutorial,
there are two relevant behaviors attached called “Player Wins” and “Number of Waves Manager”. The latter behavior
communicates with three different actors, called “Spawning Pool” (remember that one?),
“Number of Waves” and “Next Wave Button”, and it uses a new Font for the drawing called “Waves Font”.</p>

<p>The “Spawning Pool” actor still has to the “Spawn Enemies” behavior I’ve introduced in an earlier post. The “Next
Wave Button” actor has a “Button Feedback” behavior. The “Number of Waves” actor has no behaviors at all.</p>

<p>As you can see, this diagram does not visualize the entire tower defense game. Part of the trick in creating such
diagrams is omitting everything you don’t need.</p>

<p><strong>Tip</strong>: making diagrams such as these really helps in getting a grip on your own game.</p>

<h2 id="preparations">Preparations</h2>

<p>The previous picture makes it easy to start setting up a number of new actors:</p>

<ul>
  <li>Number of Waves actor: this is just a simple actor with a nice skull icon from part 8.</li>
  <li>You Win Message actor: this one is similar to the You Lost message I created earlier,
and it contains the existing “Message” behavior</li>
  <li>Waves Font: a copy of the Score Font, but using slightly different colors to match the colors of our skull</li>
  <li>Next Wave Button actor: a simple actor containing a button which I created on this website.</li>
  <li>Button Feedback behavior: a simple design mode actor behavior to show some feedback when hovering over the button.</li>
</ul>

<p><img src="/images/stencyl/step10-2.png" alt="" /></p>

<p>And of course, because I will need them later on:</p>

<ul>
  <li>a design mode scene behavior called “Number of Waves Manager”</li>
  <li>a design mode scene behavior called “Player Wins”</li>
</ul>

<p>You can attach these behaviors to the test scene; their contents will be explained in the remainder of this tutorial.</p>

<p>If you haven’t done so already, now is a good time to add some extra waves to your Enemy Spawners – this will make
testing so much easier later on.</p>

<h2 id="counting-waves">Counting Waves</h2>

<p>It’s time to do some thinking again. As I pointed out above, we will need some information to decide if we have won.
Let’s start with some definitions:</p>

<ul>
  <li>Active Spawner – an enemy spawner that is currently busy spawning enemies</li>
  <li>Active Enemy – an enemy that has been spawned, has not yet been killed by a tower and has not yet passed the finish
line.</li>
</ul>

<p>Based on these definitions, we can now determine if a wave has passed:</p>

<p><em>A wave has passed if there are no more active spawners and if there are no more active enemies.</em></p>

<p>This does mean that we will need to know if a spawner is active or not. Let’s make sure this happens.</p>

<h2 id="modifying-the-enemy-spawner">Modifying the Enemy Spawner</h2>

<p>The first thing I’m going to do is to change the enemy spawner. Remember how we added a “start next wave” call in the
 “on created” event? Let’s remove that.</p>

<p>The next step is a small modification to the “start wave” event. When a new wave starts,
this behavior will trigger a new event called “spawner_started”. Following this train of thought,
let’s also modify the “execute wave” event: when all enemies for the current wave have been spawned,
let’s trigger an event called “spawner_finished”.</p>

<p>And finally, thinking ahead a bit, let’s make new custom block called ‘number of waves’:</p>

<p><img src="/images/stencyl/step10-3.png" alt="" /></p>

<p>The end-result should look like this:</p>

<p><img src="/images/stencyl/step10-4.png" alt="" /></p>

<h2 id="number-of-waves-manager">Number of Waves Manager</h2>

<p>And now everything is in place for our coup-de-grace: the Number of Waves Manager. This behavior has a number of responsibilities:</p>

<ul>
  <li>Know how many waves there will be</li>
  <li>Know which wave we’re currently spawning</li>
  <li>Draw these numbers on the screen</li>
  <li>Keep track of the number of active spawners, so we can determine if there are any active spawners left</li>
  <li>Keep track of the number of active enemies, so we can determine if there are any enemies left</li>
  <li>Draw the “Next Wave” button when required</li>
  <li>Start a new wave when the “Next Wave” button has been clicked</li>
  <li>Trigger a “no more enemies” event when all the waves have been exhausted</li>
</ul>

<p>How are we going to do this?</p>

<p>We know how many waves there will be in total by asking all the enemy spawners how many waves they have. The largest
of those numbers is the total number of waves. We will remember this in a hidden Number attribute called “Max Waves”.</p>

<p>We can keep track of the current wave by using a hidden Number attribute called “Number of Waves”. This number will
initially be 0, and it will be increased whenever a new wave starts.</p>

<p>These attributes can then be used in a “when drawing” event to draw the numbers on the screen.</p>

<p>We can also keep track of the number of active spawners by listening to the “spawner started” event introduced in the
previous section. The behavior will get a new hidden Number attribute called “Active Spawners”. This number will be
increased whenever a “spawner started” event is triggered, and it will be decreased whenever a “spawner finished”
event is triggered.</p>

<p>For the number of active enemies a new hidden Number attribute is created called “Active Enemies”. This number is
increased whenever an enemy is created, and it will be decreased whenever an enemy dies. Remember,
enemies also die when they cross the finish line.</p>

<p>If a spawner has finished, and the resulting number of active spawners is zero, it is time to show the “Next Wave”
button. This button is stored in a hidden Actor attribute called “Go Button”. The button is created and hidden in a
“When Creating” event, and it is shown here.</p>

<p>Using a Mouse Click event, we can determine if the user clicked on the “Next Wave” button. If this happens,
we call the “Start next wave” event on our enemy spawners, and hide the button again.</p>

<p>Finally, if an enemy dies, the number of active enemies is zero and the number of active spawners is zero,
we know that the current wave has finished. Now there are two choices: either there are waves left,
in which case we start a new wave, or there are no more waves left, in which case the player has won this level. Time
 to trigger a “no more enemies” event.</p>

<p>Combining all of this, we get the following behavior:</p>

<p><img src="/images/stencyl/step10-5.png" alt="" /></p>

<h2 id="you-won">You Won</h2>

<p>The “no more enemies” event is captured by the “Player Wins” behavior. This behavior just makes sure that all the
towers are disabled; it then shows the You Won message and, for now, reloads the game.</p>

<p><img src="/images/stencyl/step10-6.png" alt="" /></p>

<p>If you’re feeling adventurous, you can create new levels for your game and make sure the next level is loaded when the player has won.</p>

<h2 id="wrapping-up">Wrapping Up</h2>

<p>In this part of the tutorial, I have:</p>

<ul>
  <li>Introduced the concept winning</li>
  <li>Introduced the concept of UML diagrams</li>
  <li>Determined how all the different actors and behaviors can work together to give the player the right experience</li>
  <li>Created a lot of new actors and behaviors</li>
</ul>

<p><a href="http://www.stencyl.com/game/play/13985">The final result can be seen here</a>, and the game can be downloaded from
StencylForge under the name “Publysher – TD Tutorial #10”.</p>

<h2 id="the-end">The End?</h2>

<p>This is the end of my tutorial. My blog is filled with interesting other technologies,
but I will no longer be writing about Stencyl game development. Of course, this does not mean that it is the end
for your game!</p>

<p>By following this tutorial you have created a solid basis to experiment further on. Whenever you get stuck, don’t
hesitate to ask around in the <a href="http://community.stencyl.com/">Stencyl Forums</a> – they are filled with friendly people
who are more than willing to help you.</p>

<p>If you have created an interesting tower defense game based on this tutorial, let me know and I will give it special
attention in this blog.</p>

<p>Happy Stencyling!</p>]]></content><author><name></name></author><category term="game" /><summary type="html"><![CDATA[Stencyl Tutorial #10 for creating tower defense games]]></summary></entry><entry><title type="html">Stencyl tower defense tutorial 9</title><link href="https://www.publysher.nl/game/2012/06/11/stencyl-tower-defense-9-staying-alive.html" rel="alternate" type="text/html" title="Stencyl tower defense tutorial 9" /><published>2012-06-11T00:00:00+00:00</published><updated>2012-06-11T00:00:00+00:00</updated><id>https://www.publysher.nl/game/2012/06/11/stencyl-tower-defense-9-staying-alive</id><content type="html" xml:base="https://www.publysher.nl/game/2012/06/11/stencyl-tower-defense-9-staying-alive.html"><![CDATA[<p>Our Tower Defense game is slowly turning into a real game, but there is still a lot of work to do. For example,
most games are about winning, and therefore about losing. In this part of the tutorial I’m going to work on losing
the game. For now, winning will remain a promise :)</p>

<p><a href="http://www.stencyl.com/game/play/13086">The result of this part can be seen here</a>; you can also find it on
StencylForge under the name “Publysher – TD Tutorial #9”.</p>

<h1 id="number-of-lives">Number of Lives</h1>

<p><del>In order to be able to lose, I will keep track of the number of lives. Every time an enemy reaches the finish line,
the player loses one live. When the player has no more lives remaining, he has lost the game. Of course,
the current number of lives has to be visible so the player knows how he’s doing.</del></p>

<p>Until now, we have only created Actor Behaviors. However, the number of lives of the player is not related to a
specific actor but to the current level. So, this time I will create our first custom Scene Behavior.</p>

<p><strong>Tip</strong>: there are no rules for choosing between Actor behaviors and Scene behaviors – use your gut feeling,
and don’t be afraid to change it later on. You will get better at it over time.</p>

<p>But first some preparations. I started out by copying the Score Font to a new font called Lives Font and changed the
colors to white and red. I also created an actor called “Number of Lives”, used
<a href="http://www.iconfinder.com/icondetails/3547/16/favourite_heart_love_package_icon?r=1">this heart from iconfinder.com</a>
as its default animation and made it a member of the group “Visual Effects”.</p>

<p>Now it is time to create a new Design Mode Scene Behavior called “Number of Lives Manager”. It will work like this:</p>

<ul>
  <li>When the behavior is created, it will draw the Heart icon on the upper left screen;</li>
  <li>When the scene is redrawn, the behavior will draw the remaining number of lives next to the Heart;</li>
  <li>The behavior will have a custom block “decrease number of lives by [amount]” – this will decrease the remaining
 number of lives. However, it will also make sure the remaining number of lives is never smaller than zero. When
 the remaining number of lives reaches 0, it will trigger an event called “no_more_lives”. This event will be
 triggered exactly once.</li>
</ul>

<p>So, we will need a few attributes:</p>

<ul>
  <li>a Number attribute “Number of Lives” – this will be used to configure the number of lives</li>
  <li>a hidden Number attribute “Current Number of Lives” – this will be used to keep track of the number of lives
remaining</li>
  <li>a hidden Actor attribute “Number of Lives Actor” – this will be used to keep track of the Heart icon</li>
  <li>a hidden Boolean attribute “No More Lives Triggered?” – this will be used to ensure we will trigger the
“no_more_lives” event exactly once.</li>
</ul>

<p><img src="/images/stencyl/step9-1.png" alt="" /></p>

<p><img src="/images/stencyl/step9-2.png" alt="" /></p>

<p><img src="/images/stencyl/step9-3.png" alt="" /></p>

<p>Attach this behavior to the Test Scene, set the Number of Lives attribute to 10 and play-test your game.</p>

<h2 id="crossing-the-line">Crossing The Line</h2>

<p><del>Now that we have lives, it is time to lose them. Let’s start by creating a Finish Line actor and put it in a new Collision Group called “Finish Line”. Using Pencyl, I created a nice black and white checkerboard pattern and added it to the scene.</del></p>

<p><img src="/images/stencyl/step9-4.png" alt="" /></p>

<p>Whenever an enemy crosses the finish line, it should cost one live. But how do we detect when an enemy crosses this
line? That’s where Stencyl’s built-in collision detection can help us.</p>

<p>The first step is to determine the correct collision shape for our actor. Open the Finish Line actor and go to the
Collision tab. Remove the default collision shape by selecting the default box and pressing the Delete button. Then,
using the “Add Box” button, add a box such that it is exactly as large as the finish line:</p>

<p><img src="/images/stencyl/step9-5.png" alt="" /></p>

<p>Now we don’t want our enemies to bump into the finish line – we merely want to detect when an enemy crosses the line.
So make sure you tick the box “Is a Sensor?” on the right-hand side.</p>

<p>The last step is to make sure our Finish Line collision group is set to collide with our enemies.</p>

<p><img src="/images/stencyl/step9-6.png" alt="" /></p>

<p>Play the Test Scene again and notice how the new finish line does not seem to have any effect. However,
under the hood a lot is happening.</p>

<h2 id="losing-lives">Losing Lives</h2>

<p><del>Now it’s time to actually make use of everything we’ve set up so far. I’m going to create a new Design Mode Actor
Behavior called “Enemy Reaches Finish”. This behavior will work like this:</del></p>

<ul>
  <li>When an enemy collides with the finish line:
    <ul>
      <li>distract a certain number of lives from our current number of lives</li>
      <li>make sure the enemy becomes invincible</li>
      <li>make sure the enemy no longer gives points when killed</li>
      <li>add some nice visual feedback</li>
    </ul>
  </li>
</ul>

<p>This implies the following attributes:</p>
<ul>
  <li>a Number attribute called “Number of Lives” – this is the number of lives we will distract from the current number
of lives when the enemy reaches the finish line. Set the default to 1.</li>
  <li>a hidden Boolean attribute called “Reached FInish Line” – this attribute will be used to ensure we will only collide
once.</li>
</ul>

<p>and the following code:</p>

<p><img src="/images/stencyl/step9-8.png" alt="" /></p>

<p><img src="/images/stencyl/step9-9.png" alt="" /></p>

<p>Add this behavior to every enemy, play the game and behold! Enemies crossing the line will now decrease the current
number of lives.</p>

<h2 id="you-lost">You Lost</h2>

<p><del>When the current number of lives reaches zero, our behavior triggers the no_more_lives event. Let’s use this event
to inform the player about this horrible event. When the player loses, a big You Lose message should appear,
after which the level should restart.</del></p>

<p>I started out by using my favorite graphics program to create a big You Lost graphic. I then created an actor called
“You Lost Message”, and put it in a new collision group called “Messages”.</p>

<p>The next step was to create a new Design Mode Actor Behavior called “Message” and attach it to the “You Lost Message”.
For now, this behavior consists of a “When Created” block and a custom block called “Show message”:</p>

<p><img src="/images/stencyl/step9-10.png" alt="" /></p>

<p><img src="/images/stencyl/step9-11.png" alt="" /></p>

<p><img src="/images/stencyl/step9-12.png" alt="" /></p>

<p>Did you notice anything special? The “show message” block returns the number of seconds it will take to actually show
the message.  This is a small trick to ensure that other behaviors can wait exactly as long as needed for the
animation to complete.</p>

<p>Everything comes together in the final behavior, a Design Mode Scene Behavior called “Player Dies”. This behavior has
one custom event block: “when [no_more_lives] happened” which:</p>

<ul>
  <li>Ensures that all enemies stand still and can no longer be killed;</li>
  <li>Ensures that the towers stop shooting at enemies;</li>
  <li>Ensures that the enemy spawners stop spawning enemies;</li>
  <li>Ensures that the player can no longer create new towers;</li>
  <li>Shows the You Lost message;</li>
  <li>Reloads the scene;</li>
</ul>

<p><img src="/images/stencyl/step9-16.png" alt="" /></p>

<p><img src="/images/stencyl/step9-15.png" alt="" /></p>

<p>This behavior was attached to the Test Scene, and playtesting shows the desired result.</p>

<h2 id="a-nasty-bug">A Nasty Bug</h2>

<p><del>Or did it? As it turns out, the game I created contained a very annoying bug: after reloading the scene,
the enemies fail to show up! At the moment I consider this a bug in Stencyl, and
<a href="http://community.stencyl.com/index.php/topic,11178.0.html">I have created a bug report</a>. Until the bug has been solved,
I have patched the “Spawn Enemies” behavior. Instead of directly modifying the Waves list attribute,
I have added a hidden “Copy of Waves” attributes which gets initialized in the “When created” block.</del></p>

<p>The “Spawn Enemies” block which was introduced in part 6 now looks like this:</p>

<p><img src="/images/stencyl/step9-13.png" alt="" /></p>

<p><img src="/images/stencyl/step9-14.png" alt="" /></p>

<p><strong>Tip</strong>: bugs happen, and usually in your own code. But sometimes it is a problem in the framework. In those cases,
do not despair and try to find a workaround.</p>

<h2 id="wrapping-up">Wrapping Up</h2>

<p>In this tutorial I have</p>

<ul>
  <li>Added a new counter to measure the number of remaining lives</li>
  <li>Added a finish line</li>
  <li>Used collision detection to detect when enemies cross the finish line and tied this to the remaining lives</li>
  <li>Created a message to tell the player he lost</li>
  <li>Encountered an interesting Stencyl bug</li>
</ul>

<p><a href="http://www.stencyl.com/game/play/13086">The final result can be seen here</a>, and the game can be downloaded from
StencylForge under the name “Publysher – TD Tutorial #9”.</p>

<p><a href="/game/2012/08/04/stencyl-tower-defense-10-do-wave.html">Now continue with the next part</a> where the player gets the opportunity to win.</p>]]></content><author><name></name></author><category term="game" /><summary type="html"><![CDATA[Stencyl Tutorial #9 for creating tower defense games]]></summary></entry></feed>