<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Keir Whitlock on Medium]]></title>
        <description><![CDATA[Stories by Keir Whitlock on Medium]]></description>
        <link>https://medium.com/@keirwhitlock?source=rss-827597f1780d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*BHUKchXfZQbv4i6MY0UU7A.jpeg</url>
            <title>Stories by Keir Whitlock on Medium</title>
            <link>https://medium.com/@keirwhitlock?source=rss-827597f1780d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:10:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@keirwhitlock/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Run Netflix BLESS SSH Certificate Authority in AWS Lambda]]></title>
            <link>https://medium.com/swlh/run-netflix-bless-ssh-certificate-authority-in-aws-lambda-f507a620e42?source=rss-827597f1780d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f507a620e42</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[ca]]></category>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[Keir Whitlock]]></dc:creator>
            <pubDate>Thu, 26 Dec 2019 16:15:43 GMT</pubDate>
            <atom:updated>2019-12-27T06:11:43.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ck7NBh2NnPqIvN7jefJWDw.jpeg" /></figure><h3>Issue Short Lived User Certs for SSH Access</h3><p>I found the following video posted on my company’s intranet the other week and really enjoyed Russell Lewis’ talk on how Netflix are using SSH Certificates and the dangers of mismanaging your SSH keys.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJwLGsWYVjqU%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJwLGsWYVjqU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJwLGsWYVjqU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7159a9eb3879f944ebfa59fd6d564cfd/href">https://medium.com/media/7159a9eb3879f944ebfa59fd6d564cfd/href</a></iframe><p>I’d never really had much exposure to SSH Certificates, aside from my own personal reading about at home about a year ago.</p><p>As a cloud user at home and at work, in particular Amazon Web Services (AWS), I was intrigued about trying out Netflix’s BLESS tool in AWS Lambda, to issue users with temporary (short lived) CA signed SSH Certificates to authenticate SSH access to servers.</p><p>I spent some time looking into BLESS and what it can do, and setup up a mock environment of my own in AWS to see what it’s all about; and thought I’d log my initial findings here in a small post for others to read.</p><h3>Prerequisites</h3><ol><li>AWS Account</li><li>KMS Key</li><li>Python Lambda Function</li></ol><p>You will need an account in AWS account with suitable permissions to set this up. Netflix recommend you have a completely isolated AWS account with just BLESS running inside to keep it away from other concerns. As this is just a mock setup, I have used the same account for both BLESS and other services.</p><p>You will also need a KMS key in the AWS Region(s) you want to operate in. As KMS is regional, you’ll have to create one in each region you want to use BLESS in. It will be needed later to encrypt your CA Certificate Key Pair Passphrase. The BLESS config file bless_deploy.cfg caters for multiple regions by being about to declare a base64 encoded string for each region.</p><pre>$ export BLESS_REGION=eu-west-2</pre><pre>$ aws kms create-alias \<br>            --region $BLESS_REGION \<br>            --alias-name alias/bless \<br>            --target-key-id \<br>$(aws kms create-key --region $BLESS_REGION | jq -r .KeyMetadata.KeyId)</pre><p>You will also need to setup an AWS Lambda function, to upload our deployment artifact to, with permissions to access your KMS key. It will be python runtime and for this post’s example the handler will be bless_lambda_user.lambda_handler_user</p><h3>Setting up your Environment</h3><h4>Download the BLESS Code</h4><p>The official repository lives at <a href="https://github.com/Netflix/bless">Netflix/bless</a> on GitHub.</p><p><a href="https://github.com/Netflix/bless">Netflix/bless</a></p><p>However in my initial setup, I was hit with errors, and later found there was an open <a href="https://github.com/Netflix/bless/pull/99">Pull Request</a> to address a bug with the latest version of marshmallow ; The PR is still open at time of writing.</p><p>As a quick temporary step, I cloned the official repository and added NeolithEra’s repo as another git remote and checked out their branch to work on.</p><p>$ git clone git@github.com:Netflix/bless.git</p><pre>$ git remote add NeolithEra <a href="/service/mailto:git@github.com">git@github.com</a>:NeolithEra/bless.git<br>$ git fetch NeolithEra<br>$ git checkout NeolithEra/master</pre><h4>Setup Python venv and Download Dependancies</h4><p>The repository includes a Makefile to help users get setup quickly in a few simple commands.</p><p>Start by creating and activating a virtual environment to work from:</p><pre>$ python3 -m venv venv<br>$ source venv/bin/activate</pre><p>pip install all the code dependencies:</p><pre>$ make develop</pre><p>Run the tests:</p><pre>$ make test</pre><p>Hopefully all the tests pass for you…</p><h4>Package up Dependancies</h4><p>AWS Lambda requires the runtime code and its dependancies to be uploaded together in a single artifact. Run the lambda-deps make command to save all your python dependancies in a local directory.</p><p>$ make lambda-deps</p><p>Behind the scenes the Makefile is spinning up a Docker container of amazonlinux:2 and pip installing all the requirements into the aws_lambda_libs folder.</p><h3>Setting up your Certificate Authority (CA)</h3><h4>Generate a CA Certificate Key Pair</h4><p>Use ssh-keygen to generate a new key pair for you, and be sure to add a <strong>strong</strong> passphrase to protect it with.</p><p>We’ll make use of KMS later to encrypt the passphrase and allow only our lambda function to decrypt it on the fly when required.</p><pre>$ ssh-keygen -t rsa -b 4096 -m PEM -f cas -C &quot;SSH CA Key&quot;</pre><h4>Encrypt your CA Key Pair Passphrase with AWS KMS Keys</h4><p>Get the KMS keyID for your region and use the AWS Cli to encrypt you CA passphrase that will be later used in your BLESS config file.</p><p>It needs to be base64 encoded in the config file.</p><pre>$ aws kms encrypt \<br>    --key-id $(aws kms describe-key --region eu-west-2 --key-id alias/bless | jq -r .KeyMetadata.KeyId) \<br>    --plaintext Password123 \<br>    --region eu-west-2 | jq -r .CiphertextBlob | base64</pre><h3>Configure, Package up &amp; Deploy your Lambda Function</h3><p>Create a directory for your BLESS config and key that will be bundled in the Lambda artifact.</p><p>There’s a sample configuration that you can use and edit for your setup available in the git repository.</p><p>Copy your config and private CA key into the configs directory.</p><pre>$ mkdir lambda_configs<br>$ cp bless/config/bless_deploy_example.cfg lambda_configs/bless_deploy.cfg <br>$ cp cas lambda_configs/cas.priv</pre><h4>Update the Bless CA section with your CA Passphrase and Filename</h4><p>$ vim lambda_configs/bless_deploy.cfg</p><p>The region in the variable below is the same one(s) used to encrypt your passphrase with KMS above. If you have encrypted the passphrase with multiple KMS keys in multiple regions, you’ll need to add a variable for each.</p><pre>[Bless CA]<br>eu-wast-2_password = &lt;base64 encoded encrypted passphrase&gt;<br>ca_private_key_file = cas.priv</pre><h4>Bundle up your Lambda Artifact</h4><p>$ make publish</p><pre>$ ls -l publish<br>total 32024<br>drwxr-xr-x  50 keirwhitlock  staff      1600 24 Dec 19:36 bless_lambda<br>-rw-r--r--   1 keirwhitlock  staff  16165660 24 Dec 19:36 bless_lambda.zip</pre><h4>Upload to AWS Lambda</h4><p>Upload the resulting bless_lambda.zip to your AWS Lambda function.</p><ol><li>Open the AWS Lambda console.</li><li>Choose Functions on the navigation pane, and then open your function.</li><li>In the Function code section, expand the Code entry type drop-down list, and then choose Upload a .ZIP file.</li><li>Choose Upload, and then select your .zip file.</li><li>Choose Save.</li></ol><h3>Server Side Configuration</h3><p>Launch an instance to test your BLESS signed certs from. Any linux OS should do. I used <strong>Amazon Linux 2 AMI</strong> purely because it was top in the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44L3Icx1wLUx__KxdC8iew.png" /></figure><h4>Trust the CA Key on the Server</h4><p>Now you need to setup your server(s) to trust your CA certificate and if you wish, restrict with users can log in.</p><p>Add the following line to your sshd_config :</p><p>TrustedUserCAKeys /etc/ssh/cas.pub</p><p>Then scp a copy your CA’s <strong>public</strong> key to the server to /etc/ssh.</p><p>Be sure to restrict it to root privileges &amp; restart sshd when done.</p><p>$ systemctl restart sshd.service</p><h4>Restrict which users can log on</h4><p>I created an additional local user to test with other than the default ec2-user</p><p>On the server create a file in /etc/ssh with the names of all the users allowed to log in via this method</p><p>$ echo keirtest &gt; /etc/ssh/auth_principals</p><p>.. and refer to it in the /etc/ssh/sshd_config with the <em>AuthorizedPrincipalsFile</em> parameter:</p><p>AuthorizedPrincipalsFile /etc/ssh/auth_principals</p><p>Once added, restart sshd</p><p>$ systemctl restart sshd.service</p><h4>Testing your BLESS Setup</h4><p>The Netflix team have included a bless_client.py script to allow you to test your lambda function is working correctly and generate your signed certificate from your local SSH key.</p><p>If you watched the video I included at the start, you’ll see that Netflix use a <em>Bastion </em>host for their users to first connect to, and then jump from there to their desired destination, using BLESS to issue a short lived cert at that point.</p><p>As such the client script is expecting some details on where you are coming from and going to, so that BLESS can log this information in AWS CloudWatch logs for auditing purposes.</p><p>Get your local <strong>public</strong> ssh key signed by your BLESS lambda function:</p><pre>$ ./bless_client.py region lambda_function_name bastion_user bastion_user_ip remote_usernames bastion_ips bastion_command &lt;id_rsa.pub to sign&gt; &lt;output id_rsa-cert.pub&gt;</pre><p>View your signed certificates details:</p><pre>$ ssh-keygen -L -f id_rsa-cert.pub</pre><p>Now try and connect to your test instance via SSH, passing both your pub key and the signed pub key:</p><pre>$ ssh &lt;REMOTE USERNAME&gt;@&lt;REMOTE IP&gt; -i &lt;output id_rsa-cert.pub&gt; -i &lt;id_rsa.pub to sign&gt;</pre><h3>Conclusion</h3><p>I’ve only touched on what you can do with BLESS here in this post, but I’d encourage anyone interested in securing your systems in this manner to watch Russell’s YouTube <a href="https://www.youtube.com/watch?v=JwLGsWYVjqU">video</a> &amp; give it a go.</p><p>Next I’m going to explore some of the other abilities SSH Certificates &amp; BLESS can give you. Such as:</p><ol><li>Create a bastion host to jump from and log the session details.</li><li>Setup host certificates; so you never get that unknown host warning on valid servers.</li><li>Setup log auditing and alarms for improper SSH use.</li></ol><h3>Further Reading</h3><pre>1. <a href="https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/sec-signing_ssh_certificates">Creating SSH Certificates</a> - Red Hat Docs<br>2. <a href="https://github.com/Netflix/bless/blob/master/README.md">Netflix BLESS README.md</a><br>3. <a href="https://smallstep.com/blog/use-ssh-certificates/">Blog</a> by Mike Milone advocating the use of SSH Certificates</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f507a620e42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/run-netflix-bless-ssh-certificate-authority-in-aws-lambda-f507a620e42">Run Netflix BLESS SSH Certificate Authority in AWS Lambda</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Molecule & Gitlab-CI to Automate Testing of Ansible Roles]]></title>
            <link>https://medium.com/@keirwhitlock/use-molecule-gitlab-ci-to-automate-testing-of-ansible-roles-9d745cd89db1?source=rss-827597f1780d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d745cd89db1</guid>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[molecule]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Keir Whitlock]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 18:22:17 GMT</pubDate>
            <atom:updated>2019-12-23T18:22:17.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISRkSiOhGkniaoDCXuli2A.jpeg" /></figure><h3>Automate your testing in the cloud</h3><p>Following on from my <a href="https://medium.com/@keirwhitlock/using-molecule-to-test-ansible-roles-5df6fb341b3e">previous post</a> where I was showing how you can develop and test your <a href="https://docs.ansible.com/">Ansible</a> roles locally using <a href="https://www.docker.com/">Docker</a>.</p><p>In this post I am going to take things one stage further, and have Gitlab detect changes on our repository and run the Molecule tests on an instance in AWS.</p><h3>Prerequisites</h3><p>You will need an account of <a href="https://about.gitlab.com/">Gitlab-CI </a>and <a href="https://aws.amazon.com/">Amazon Web Services (AWS)</a> in order to follow along with the steps below.</p><h3>Initialise a Molecule Scenario for EC2</h3><p><a href="https://molecule.readthedocs.io/en/stable/getting-started.html#molecule-scenarios">Scenarios</a> are an isolation for molecule, to be able to test your role in a particular way. For example the default scenario unless modified by the -d driver flag is to use Docker.</p><p>Creating another scenario for our EC2 driver allows us to configure things separately from that of the local Docker setup.</p><p>Lets create a scenario that will be used to test our role in AWS EC2.</p><pre>$ molecule init scenario -d ec2 -r ansible.role.example -s aws-ec2</pre><pre>$ ls -l molecule/aws-ec2<br>INSTALL.rst  create.yml   destroy.yml  molecule.yml playbook.yml prepare.yml  tests</pre><p>Like the Docker driver before creating a Dockerfile.j2, Molecule’s EC2 driver has added a create.yml and destroy.yml for use by Molecule to create and terminate an instance in AWS for us.</p><p>Update platforms section inmolecule.yml with an EC2 AMI ID, and VPC subnet ID that reflects your environment in AWS.</p><pre>platforms:<br>  - name: instance<br>    image: ami-05945867d79b7d926<br>    instance_type: t2.micro<br>    vpc_subnet_id: subnet-vb562eu8</pre><p>I have found that<em> line 62</em> of the create.yml file, the use of ec2_ami_facts is now <em>deprecated</em> and should be changed to ec2_ami_info . It wont stop you from continuing if you leave it, however it will tell you about the deprecation each time a new instance is spun up.</p><pre>- name: Get the ec2 ami(s) by owner and name, if image not set<br>  ec2_ami_info:<br>    owners: &quot;{{ item.image_owner }}&quot;<br>      filters:<br>        name: &quot;{{ item.image_name }}&quot;<br>  loop: &quot;{{ molecule_yml.platforms }}&quot;<br>  when: item.image is not defined<br>  register: ami_facts</pre><h3>Testing Locally First</h3><h4>Setting up your Environment</h4><p>You’ll need to export your AWS access key and secret access key to test locally; as well as the region.</p><pre>$ export EC2_REGION=eu-west-2<br>$ export AWS_ACCESS_KEY_ID=ACCESSKEY<br>$ export AWS_SECRET_ACCESS_KEY=SECRETACCESSKEY</pre><h4>Run a Converge to Test Connectivity to AWS</h4><pre>$ molecule converge -s aws-ec2</pre><p>This should launch an EC2 instance in AWS. Once the instance is available molecule will run our role in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cuaCQLma4GJnqdjrXpL7A.png" /></figure><pre>TASK [Wait for SSH] ************************************************************<br>    ok: [localhost] =&gt; (item={&#39;address&#39;: &#39;3.8.91.90&#39;, &#39;identity_file&#39;: &#39;/Users/keirwhitlock/.cache/molecule/ansible.role.example/aws-ec2/ssh_key&#39;, &#39;instance&#39;: &#39;instance&#39;, &#39;instance_ids&#39;: [&#39;i-0ba2b57eed44ca426&#39;], &#39;port&#39;: 22, &#39;user&#39;: &#39;ubuntu&#39;})</pre><pre>TASK [Wait for boot process to finish] *****************************************<br>    Pausing for 120 seconds<br>    (ctrl+C then &#39;C&#39; = continue early, ctrl+C then &#39;A&#39; = abort)</pre><p>Once the converge is finished, you can SSH onto the instance if you wish, but for now lets clean things up and add some tests to run.</p><p>$ molecule destroy -s aws-ec2</p><h4>Writing a Testinfra Test</h4><p>As before in my <a href="https://medium.com/@keirwhitlock/using-molecule-to-test-ansible-roles-5df6fb341b3e">previous post</a>, I am going to copy the test that checks httpd is installed to our aws-ec2 scenario molecule/aws-ec2/tests/test_default.py</p><pre>def test_httpd_installed(host):<br>    assert host.package(&quot;httpd&quot;).is_installed</pre><p>Lets run a full <em>test</em> run and see if it passes</p><p>$ molecule test -s aws-ec2</p><p>This will launch and instance, install httpd for us; run the Teastinfra tests and then terminate the instance again.</p><pre>...<br>--&gt; Executing Testinfra tests found in /Users/keirwhitlock/development/ansible.role.example/molecule/aws-ec2/tests/...<br>    ============================= test session starts ==============================<br>    platform darwin -- Python 3.6.2, pytest-5.3.2, py-1.8.0, pluggy-0.13.1<br>    rootdir: /Users/keirwhitlock/development/ansible.role.example/molecule/aws-ec2<br>    plugins: testinfra-3.3.0<br>collected 2 items</pre><pre>tests/test_default.py ..                                                 [100%]</pre><pre>============================== 2 passed in 3.64s ===============================<br>Verifier completed successfully.<br>--&gt; Scenario: &#39;aws-ec2&#39;<br>--&gt; Action: &#39;cleanup&#39;<br>Skipping, cleanup playbook not configured.<br>--&gt; Scenario: &#39;aws-ec2&#39;<br>--&gt; Action: &#39;destroy&#39;</pre><pre>PLAY [Destroy] *****************************************************************</pre><pre>TASK [Populate instance config] ************************************************<br>    ok: [localhost]</pre><pre>TASK [Destroy molecule instance(s)] ********************************************<br>    changed: [localhost] =&gt; (item=None)<br>    changed: [localhost]</pre><pre>TASK [Wait for instance(s) deletion to complete] *******************************<br>    FAILED - RETRYING: Wait for instance(s) deletion to complete (300 retries left).<br>    changed: [localhost] =&gt; (item=None)<br>    changed: [localhost]</pre><pre>TASK [Populate instance config] ************************************************<br>    ok: [localhost]</pre><pre>TASK [Dump instance config] ****************************************************<br>    changed: [localhost]</pre><pre>PLAY RECAP *********************************************************************<br>    localhost                  : ok=5    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0</pre><pre>--&gt; Pruning extra files from scenario ephemeral directory</pre><p>Good! Looks like our basic setup via AWS is working. Now for Gitlab-CI to run these tests for us on code commit.</p><h3>Setting up GitLab-CI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_O3OUrtyLcl5fSCaQRM0w.jpeg" /></figure><h4>New Project</h4><p>Create a new project to store your Ansible code in and to run our pipeline from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0v05HLjBqkqDQt317iH5Q.png" /></figure><p>Initialise your git repository locally and push up your code.</p><pre>git init<br>git remote add origin <a href="/service/mailto:git@gitlab.com">git@gitlab.com</a>:kwhitlock/ansible.role.example.git<br>git add .<br>git commit -m &quot;Initial commit&quot;<br>git push -u origin master</pre><h4>Add CI/CD Variables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nupfyXel1KGaK1JQSXlaFg.png" /></figure><p>Within your project add in the AWS environment variables to your CI/CD settings</p><ol><li>EC2_REGION</li><li>AWS_ACCESS_KEY_ID</li><li>AWS_SECRET_ACCESS_KEY</li></ol><p>Be sure to set your AWS Credentials to <strong>Protected</strong> &amp; <strong>Masked</strong> so that they cannot be changed or viewed in any log output.</p><h4>Create a .gitlab-ci.yml Pipeline Config</h4><p>In the top level directory for your role, add in a .gitlab-ci.yml file to detail to Gitlab how you want to run your tests.</p><pre>---<br>default:<br>  image: python:3</pre><pre>before_script:<br>    - python3 -m venv ../molecule-ve<br>    - source ../molecule-ve/bin/activate<br>    - pip install molecule boto boto3 botocore</pre><pre>test:<br>    script:<br>    - molecule test -s aws-ec2</pre><p>Here we are creating a <em>venv</em> one level above our working directory as the code, otherwise this can cause issues with the <em>yamllint</em> process.</p><p>If you do have your <em>venv</em> or other files in the working directory, and need to ignore them; you can edit the lint section ofmolecule.yml file.</p><p>molecule/aws-ec2/molecule.yml</p><pre>lint:<br>  name: yamllint<br>  options:<br>    config-data:<br>      ignore: molecule-ve</pre><p>Once you commit and push your edited files &amp;.gitlab-ci.yml to the repository, Gitlab will read the file and begin running the steps to run our Molecule role and tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*bRDsuCMVPWD85t5Vj782bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7A_faJGoYgWAVSBnjz8lA.png" /></figure><p>As you can see the test section in the pipeline ran, and conducted the 2 tests that are in the tests/test_default.py file.</p><h3>Local &amp; Remote Development</h3><p>So now we can develop Ansible roles locally and quickly; and test their validity using Docker on your laptop; and once its complete and you’re happy push your changes to a code repository and have it run the tests again in AWS.</p><p>This way you can write a whole different suite of tests for the AWS scenario(s). Perhaps test that it can communicate properly with another <a href="https://aws.amazon.com/?nc2=h_lg">AWS</a> service like <a href="https://aws.amazon.com/elasticache/redis/">AWS Elasticache</a> or you want to launch several different AMIs simultaneously and test your role on different OSs or Instance types.</p><h3>Conclusion</h3><p>This is only a brief example of how you might use a CICD tool like Gitlab, and Molecule to help develop your Ansible roles rapidly and with confidence that they will work in all the conceivable scenarios you can think of.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d745cd89db1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Molecule to Test Ansible Roles]]></title>
            <link>https://medium.com/@keirwhitlock/using-molecule-to-test-ansible-roles-5df6fb341b3e?source=rss-827597f1780d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5df6fb341b3e</guid>
            <category><![CDATA[system-configuration]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[molecule]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[testinfra]]></category>
            <dc:creator><![CDATA[Keir Whitlock]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 11:15:02 GMT</pubDate>
            <atom:updated>2019-12-23T11:15:02.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISRkSiOhGkniaoDCXuli2A.jpeg" /></figure><h3>Gain Confidence in your Ansible Roles by Writing Tests</h3><h3>Prerequisites</h3><p>If you wish to use <a href="https://molecule.readthedocs.io/en/stable/">Molecule</a> for local development, and use a <a href="https://www.docker.com/?utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=dockerhomepage&amp;utm_content=nemea&amp;utm_term=dockerhomepage&amp;utm_budget=growth&amp;gclid=EAIaIQobChMIk-SevsXL5gIV0kPTCh1rwQEmEAAYAiAAEgI1gfD_BwE">Docker</a> container to test your roles on; you will of course need docker installed locally. I am using <a href="https://docs.docker.com/docker-for-mac/">docker-for-mac</a>; which works really well.</p><h3>Setting up your environment</h3><p>I like to use <a href="https://www.python.org/">python’s</a> <a href="https://docs.python-guide.org/dev/virtualenvs/">virtualenv</a> to separate concerns and keep each working environment I may be using, isolated.</p><pre>$ virtualenv --no-site-packages venv<br>$ source venv/bin/activate</pre><p>Once activated; install molecule</p><p>$ pip install molecule</p><p>This should also install <a href="https://www.ansible.com/">Ansible</a>; and various other dependancies.</p><p>You might need the Docker driver for Molecule also, so install that too.</p><p>$ pip install molecule[docker]</p><h3>Use Molecule to create a new role</h3><pre>$ molecule init role -d docker -r ansible.role.example</pre><p>This will create a generic role structure from ansible-galaxy as well as an additional molecule directory, from which all the tests and setup for molecule will be kept.</p><p>Although I have specified the docker driver here using -d docker it is in fact the default driver, if non were specified.</p><p>If you look inside the molecule directory you will see it has given you a Dockerfile.j2 from which molecule will use to spin up a new docker container to test your task from.</p><p>As molecule uses ansible-galaxy to create the templated role, there are metadata checks in place. Within meta/main.yml there are 5 sections that need to be filled in</p><ol><li>author</li><li>description</li><li>company</li><li>license</li><li>platform</li></ol><p>Otherwise the molecule lint sequence will fail. Alternatively you can rename the yml file to something else for now.</p><p>$ mv meta/main.yml meta/main</p><h4>Running a Molecule test</h4><p>Before writing anything, run a molecule test and see what the output is.</p><pre>$ cd ansible.role.example<br>$ molecule test<br>--&gt; Validating schema /Users/keirwhitlock/development/ansible.role.example/molecule/default/molecule.yml.<br>Validation completed successfully.<br>--&gt; Test matrix</pre><pre>└── default<br>    ├── lint<br>    ├── dependency<br>    ├── cleanup<br>    ├── destroy<br>    ├── syntax<br>    ├── create<br>    ├── prepare<br>    ├── converge<br>    ├── idempotence<br>    ├── side_effect<br>    ├── verify<br>    ├── cleanup<br>    └── destroy</pre><pre>--&gt; Scenario: &#39;default&#39;<br>--&gt; Action: &#39;lint&#39;<br>--&gt; Executing Yamllint on files found in /Users/keirwhitlock/development/ansible.role.example/...<br>Lint completed successfully.</pre><p>I’ve cut this short to save screen space; but you should of seen molecule spin up a container, run its test(s) and then delete the container again.</p><p>Now that you have molecule up and running and a base role created, you can no go ahead and start adding your tasks as you normally would have, and you can run molecule test at anytime to get molecule to spin up a test box and try out your roles tasks.</p><p>If you are continuously iterating your development of your role, you might not want the docker container to constantly be created and destroyed each time you run molecule test . If this is the case you can use molecule converge instead, which will leave your container running. Once you are done you can issue the molecule destroy command to delete it.</p><p>NB: The molecule.yml is used to setup the environment for molecule to use, and the default image for docker to spin up is centos:7 ; so you will need to edit this if this is incorrect for you.</p><h4>Add some tasks to your role</h4><p>Just to illustrate how you might use molecule for your development. I’m going to add a basic task to my ansible.role.example role.</p><p>So within tasks/main.yml I’m going to add a task to install httpd .</p><pre>---<br># tasks file for ansible.role.example</pre><pre>- name: install apache package<br>  package:<br>    name: httpd<br>    state: present</pre><p>Run a converge to test</p><p>$ molecule converge</p><p>and you will see that molecule is using our role on the docker test box, and installing httpd as intended.</p><pre>--&gt; Action: &#39;converge&#39;</pre><pre>PLAY [Converge] ****************************************************************</pre><pre>TASK [Gathering Facts] *********************************************************<br>    ok: [instance]</pre><pre>TASK [ansible.role.example : install apache package] ***************************<br>    changed: [instance]</pre><pre>PLAY RECAP *********************************************************************<br>    instance                   : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0</pre><p>But how can we be extra certain the package is installed correctly?</p><h4>Writing Tests</h4><p>Molecule out the box uses <a href="https://testinfra.readthedocs.io/en/latest/index.html">testinfra</a> to allow users to write python tests to check the test systems they are applying their Ansible roles to, for correctness.</p><p>Within your default scenario, within the molecule directory there is a python script where you can add your tests.</p><p>molecule/default/tests/test_default.py</p><p>Inside you will see that there is already a example test there for you, which is checking for the existence of the /etc/hosts file. This is the 1 test you may have noticed in the molecule test output earlier.</p><p>Testinfra comes out the box with various <a href="https://testinfra.readthedocs.io/en/latest/modules.html">modules</a> that can be used for testing your Ansible with. As we have just installed the httpd package, lets test that this exists. Testinfra has a <a href="https://testinfra.readthedocs.io/en/latest/modules.html#testinfra.modules.package.Package">package</a> class for this very thing.</p><p>Adding a simple test for this is simply</p><pre>def test_httpd_installed(host):<br>    assert host.package(&quot;httpd&quot;).is_installed</pre><p>Now lets run the verify command to run our tests and hopefully things should pass.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd04f824e29f7dcfddc2d43e502f0127/href">https://medium.com/media/fd04f824e29f7dcfddc2d43e502f0127/href</a></iframe><p>Good! Now we have 2 tests that are passing. Just for illustration I’ll show you a snippet of the output when the tests do not pass.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd16bfa82e07c7c315f56e5fc36fb6ba/href">https://medium.com/media/fd16bfa82e07c7c315f56e5fc36fb6ba/href</a></iframe><p>Here I have changed the test to look for apache instead of httpd and as a result our test has failed.</p><h3>Conclusion</h3><p>So as you can see from my quick example; you can use Molecule to help you in the process of developing an Ansible role. Spinning up a new container to test your role’s tasks against, and even the ability writing additional tests, (which can be as simple or as complex as you feel you need), in order to assure yourself that your role is configuring your systems as you expect.</p><p>Next time, I’m going to take the process one step further, and have <a href="https://about.gitlab.com/">Gitlab-CI</a> detect updates to the role repositories and conduct a test run for us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5df6fb341b3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>