An overview of articles

And, or and not

Today I spent a couple of hours on a condition that contained a mistake. Let me try to help myself and describe a few situations.

Condition?

A condition in Ansible can be described in a when statement. This is a simple example:

- name: do something only to virtual instances
  debug:
    msg: "Here is a message from a guest"
  when: ansible_virtualization_role == "guest"

And

It’s possible to describe multiple conditions. In Ansible, the when statement can be a string (see above) or a list:

- name: do something only to Red Hat virtual instances
  debug:
    msg: "Here is a message from a Red Hat guest"
  when:
    - ansible_virtualization_role == "guest"
    - ansible_os_family == "RedHat"

The above example will run when it’s both a virtual instance and it’s a Red Hat-like system.

Or

Instead of combining (‘and’) conditions, you can also allow multiple condition where either is true:

- name: do something to either Red Hat or virtual instances
  debug:
    msg: "Here is a message from a Red Hat system or a guest"
  when:
    - ansible_virtualization_role == "guest" or ansible_os_family == "RedHat"

I like to keep lines short to increase readability:

  when:
    - ansible_virtualization_role == "guest" or
      ansible_os_family == "RedHat"

And & or

You can also combine and and or:

- name: do something to a Debian or Red Hat, if it's a virtual instances
  debug:
    msg: "Here is a message from a Red Hat or Debian guest"
  when:
    - ansible_virtualization_role == "guest"
    - ansible_os_family == "RedHat" or ansible_os_family == "Debian"

In

It’s also possible to check if some pattern is in a list:

- name: make some list
  set_fact:
    allergies:
      - apples
      - bananas

- name: Test for allergies
  debug:
    msg: "A match was found: "
  when: item in allergies
  loop:
    - pears
    - milk
    - nuts
    - apples

You can have multiple lists and check multiple times:

- name: make some list
  set_fact:
    fruit:
      - apples
      - bananas
    dairy:
      - milk
      - eggs

- name: Test for allergies
  debug:
    msg: "A match was found: "
  when:
    - item in fruit or
      item in dairy
  loop:
    - pears
    - milk
    - nuts
    - apples

Negate

It’s also possible to have search in a list negatively. This is where it gets difficult: (for me!)

- name: make some list
  set_fact:
    fruit:
      - apples
      - bananas
    dairy:
      - milk
      - eggs

- name: Test for allergies
  debug:
    msg: "No match was found: "
  when:
    - item not in fruit
    - item not in dairy
  loop:
    - pears
    - milk
    - nuts
    - apples

The twist here is that both conditions (and) should not be true.

Well, I’ll certainly run into some issue again in the future, hope this helps you (and me) if you ever need a complex condition in Ansible.

Relations between containernames, setup and Galaxy

It’s not easy to find the relation between container names, facts returned from setup (or gather_facts) and Ansible Galaxy platform names.

Here is an attempt to make life a little easier:

containername ansible_distribution ansible_os_family ansible_distribution_major_version galaxy_platform galaxy_version
alpine Alpine Alpine 3 Alpine all
alpine:edge Alpine Alpine ? Alpine all
amazonlinux:1 Amazon RedHat 2018 Amazon 2018.03
amazonlinux Amazon RedHat 2 Amazon Candidate
archlinux Archlinux Archlinux ? ArchLinux all
centos:7 CentOS EL 7 EL 7
centos CentOS EL 8 EL 8
debian Debian Debian buster Debian buster
debian:unstable Debian Debian sid Debian sid
fedora Fedora RedHat 30 Fedora 30
fedora:rawhide Fedora RedHat 32 Fedora all
opensuse OpenSUSE Suse 15 opensuse all
oraclelinux:7 OracleLinux RedHat 7 EL 7
oraclelinux OracleLinux RedHat 8 EL 7
ubuntu Ubuntu Debian 18 Ubuntu bionic

Why would you write Ansible roles for multiple distributions?

I got some feedback in a discussion with the audience at DevOps Amsterdam.

My statement are:

These two contradict eachother: simplicity would mean 1 role for 1 (only my) distribution.

Hm, that’s a very fair point. Still I think writing for multiple operating systems is a good thing, for these reasons:

  1. You get a better understanding of all the operating systems. For example Ubuntu is (nearly) identical to Debian, SUSE is very similar to Red Hat.
  2. By writing for multiple distributions, the logic (in tasks/main.yml) becomes more stable.
  3. It’s just very useful to be able to switch distributions without switching roles.

Super important Ansible facts

There are some facts that I use very frequently, they are super important to me.

This is more a theraputic post for me, than it’s a great read to you. ;-)

Sometimes, actually most of the times, each operating system or distribution needs something specific. For example Apache httpd has different package named for mostly every distribution. This mapping (distro:packagename) can be done using this variable: ansible_os_family.

Try to select packages/service-names/directories/files/etc based on the most general level and work your way down to more specific when required. This results in a sort of priority list:

  1. General variable, not related to a distribution. For example: postfix_package.
  2. ansible_os_family variable, related to the type of distribution, for example: httpd_package which differs for Alpine, Archlinux, Debian, Suse and RedHat. (But is’t the same for docker images debian and ubuntu.)
  3. ansible_distribution variable when each distribution has differences. For example: reboot_requirements. CentOS needs yum-utils, but Fedora nees dnf-utils.
  4. ansible_distribution and ansible_distribution_major_version when there are differences per distribution release. For example firewall_packages. CentOS 6 and CentOS 7 need to have a different package.

Here is a list of containers and their ansible_os_family.

Container image ansible_os_family
alpine Alpine
archlinux/base Archlinux
centos RedHat
debian Debian
fedora RedHat
opensuse/leap Suse
ubuntu Debian

What I wish ansible collections would be

Ansible Collections is a way of:

  1. Packaging Ansible Content (modules/roles/playbooks).
  2. Distributing Ansible Content through Ansible Galaxy.
  3. Reducing the size of Ansible Engine.

All modules that are now in Ansible will move to Ansible Collections.

I’m not 100% sure how Ansible Collections will work in the future, but here is a guess.

From an Ansible role

I could imagine that requirements.yml will link depending modules and collections. Something like this:

---
- src: robertdebock.x
  type: role
- src: robertdebock.y
  type: collection

That structure would ensure that all modules required to run the role are going to be installed.

From an Ansible playbook repository

Identical to the role setup, I could imagine a requirements.yml that basically prepares the environment with all required dependencies, either roles or collections.

Loop dependencies

Ansible Collections can depend on other Ansible Collections.

Imagine my_collection’s requirements.yml:

---
- src: robertdebock.y
  type: collection

The Ansible Collection y could refer to my_colletion.

my_collection ---> y
       ^           |
       |           |
       +-----------+

I’m not sure how that can be resolved or prevented.

How many modules do you need?

Ansible Collections are coming. A big change in Ansible, so a stable version will likely be a good moment to go to Ansible 3. Listening to the developers, I think we can expect Ansible 3 in the spring of 2020.

Anyway, let’s get some stats:

How many modules am I using?

Thas was not so dificult to estimate: 97 modules.

What ‘weird’ modules?

A bit more difficult to answer, I’ve taken two approaches:

  1. Take the bottom of the list of “most used modules”.
  2. Walked throught the 97 modules and discover odd once.

How many ‘vendor’ modules?

I expect some Ansible Collections will be maintained by the vendors; Google (GCP), Microsoft (Azure), F5 (BigIP), yum (RedHat), etc. That’s why knowing this upfront is likely smart.

Module Times used Potential maintainer
pip 17 PyPi
apt 16 Canonical
yum 9 Red Hat
apt_key 6 Canonical
apt_repository 5 Canonical
rpm_key 4 Red Hat
zypper 3 SUSE
yum_repository 3 Red Hat
dnf 3 Red Hat/Fedora
zypper_repository 2 SUSE
zabbix_host 2 Zabbix
zabbix_group 2 Zabbix
apk 2 Alpine
tower_* 7 (combined) RedHat
redhat_subscription 1 RedHat
pacman 1 ArchLinux
bigip_* 6 (combined) F5

How often do I use what modules?

Place Module Times used
1 package 138
2 service 137
3 command 73
4 template 64
5 file 62
6 meta 27
7 assert 26
8 unarchive 24
9 lineinfile 21
10 copy 20

Wow, I’m especially surprised by two modules:

  1. command - I’m going to review if there are modules that I can use instead of command. I know very well that command should be used as a last resort, not 73 times… Painful.
  2. assert - Most roles used to see of variable met the criteria. (If a variable is defined and the type is correct.) Rather wait for role spec.

Ansible Fest Atlanta 2019

Announcements on Ansible, AWX, Molecule, Galaxy, Ansible-lint and many other produts are always done on Ansible Fest.

Here is what I picked up on Ansible Fest 2019 in Atlanta, Georgia.

Ansible Collections

Ansible if full of modules, “batteries included” is a common expression. This reduces velocity in adding modules, fixing issues with modules or adding features to modules. Ansible Collections is there to solve this issue.

Ansible will (in a couple of releases) only be the framework, without modules or plugins. Modules will have to be installed seprarately.

There are a few unknowns:

Anyway, the big take-away: Start to learn to develop or use Ansible Collections, it’s going to be important.

Here is how to develop Ansible Collections and how to use them.

AWX

AWX is refactoring components to improve development velocity and the performance of the product itself.

Data analysis

There are a few applications to analyse data and give insights on development and usage of Ansible:

There are many more perspectives, have a look.

Next Ansible Fest not in Europe

Spain seems to be the largest contributor of Ansible, but next Ansible Fest will be in San Diego.

The Contributers Summit will be in europe though.

Why “hardening” is not a role

I see many developers writing an Ansible role for hardening. Although these roles can absolutely be useful, here is why I think there is a better way.

Roles are (not always, but frequently) product centric. Think of role names like:

A role for hardening you system has the potential to cover all kinds of topics that are covered in the product specific roles.

Besides that, in my opinion a role should be:

  1. Small
  2. Cover on function

A good indicator of a role that’s too big is having multiple task files in tasks.

So my suggestion to not use a harden role, but rather have each role that you compose a system out of, use secure defaults.

Ansible Molecule tests using Red Hat UBI images

Red Hat now offers Universal Base Images(UBI). These images are stored on Red Hat’s registry:

That’s great, now everybody can test on a Red Hat container.

There are a few hoops you have to jump through to be able to use it in Travis:

Store credentials in Travis

The Red Hat Registry documents that a username and password need to be set to be able to pull:

$ docker login registry.redhat.io
Username: ${REGISTRY-SERVICE-ACCOUNT-USERNAME}
Password: ${REGISTRY-SERVICE-ACCOUNT-PASSWORD}
Login Succeeded!

$ docker pull registry.redhat.io/ubi7/ubi

You need to generate a service-account once.

Paste the username and password in Travis, under the build -> more options -> settings - environment variables.

Be sure to escape weird characters. My username contains a |, for example: foo|bar needs to be entered as foo\|bar.

Change molecule.yml

Molecule can pickup environment variables as documented.

So, your molecule.yml may end up something like this:

(Reduced example, your milage may vary)

---
dependency:
  name: galaxy
  options:
    role-file: requirements.yml
driver:
  name: docker
platforms:
  - name: bootstrap-rhel-latest
    image: ubi8/ubi
    registry:
      url: registry.redhat.io
      credentials:
        username: $registryredhatiousername
        password: $registryredhatiopassword
scenario:
  name: default

Ansible Galaxy Collections are here!

As the documentation describes:

Collections are a new way to package and distribute Ansible related content.

I write a lot of roles, roles are nice, but it’s a bit like ingredients without a recipe: A role is only a part of the whole picture.

Collections allow you to package:

So instead of [upstreaming](https://en.wikipedia.org/wiki/Upstream_(software_development) content to Ansible, you can publish or consume content yourself.

The whole process is documented and should not be difficult.

I’ve published my development_environment and only had to change these things:

1. Add galaxy.yml

namespace: "robertdebock"
name: "development_environment"
description: Install everything you need to develop Ansible roles.
version: "1.0.4"
readme: "README.md"
authors:
    - "Robert de Bock"
dependencies:
license:
    - "Apache-2.0"
tags:
    - development
    - molecule
    - ara
repository: "https://github.com/robertdebock/ansible-development-environment"
documentation: "https://github.com/robertdebock/ansible-development-environment/blob/master/README.md"
homepage: "https://robertdebock.nl"
issues: "https://github.com/robertdebock/ansible-development-environment/issues"

2. Enable Travis for the repository

Go to Travis and click Sync account. Wait a minute or so and enable the repository containing your collection.

3. Save a hidden variable in Travis

Under settings for a repository you can find Environment Variables. Add one, I called it galaxy_api_key. You’ll refer to this variable in .travis.yml later.

4. Add .travis.yml

---
language: python

install:
  - pip install mazer
  - release=$(mazer build | tail -n1 | awk '{print $NF}')

script:
  - mazer publish --api-key=${galaxy_api_key} ${release}

Bonus hint: Normally you don’t save roles, so you add something like roles/* to .gitignore, but in this case it is a part of the collection. So if you have requirements.yml, download all the roles locally using ansible-galaxy install -r roles/requirements.yml -f and include them in the commit.

Fedora 30 and above use python-3

Fedora 30 (and above) uses python 3 and start to deprecate python 2 package like python2-dnf.

Ansible 2.8 and above discover the python interpreter, but Ansible 2.7 and lower do not have this feature.

So for a while, you have to tell Ansible to use python 3. This can be done by setting the ansible_python_interpreter somewhere. Here are a few locations you could use:

1. inventory

This is quite a good location, because you could decide to give a single node this variable:

inventory/host_vars/my_host.yml:

---
ansible_python_interpreter: /usr/bin/python3

Or you could group hosts and apply a variable to it:

inventory/hosts:

[python3]
my_host

inventory/group_vars/python3.yml

---
ansible_python_interpreter: /usr/bin/python3

2. extra vars

You could start a playbook and set the ansible_python_interpreter once:

ansible-playbook my_playbook.yml --extra_vars "ansible_python_interpreter=/usr/bin/python3"

It’s not very persistent though.

3. playbook or role

You could save the variable in your playbook or role, but this makes re-using code more difficult; it will only work on machines with /usr/bin/python3:

---
- name: do something
  hosts: all

  vars:
    ansible_python_interpreter: /usr/bin/python3

  tasks:
    - name: do some task
      debug:
        msg: "Yes, it works."

4. molecule

Last case I can think of it to let Molecule set ansible_python_interpreter.

molecule/default/molecule.yml:

---
# Many parameters omitted.
provisioner:
  name: ansible
  inventory:
    group_vars:
      all:
        ansible_python_interpreter: /usr/bin/python3
# More parameters omitted.

Why you should use the Ansible set_fact module

So far it seems that the Ansible set_fact module is not required very often. I found 2 cases in the roles I write:

In the awx role:

- name: pick most recent tag
  set_fact:
    awx_version: ""
  with_items:
    - ""

In the zabbix_server role:

- name: find version of zabbix-server-mysql
  set_fact:
    zabbix_server_version: ""

In both cases a “complex” variable strucure is saved into a simpler to call variable name.

Variables that are constructed of other variables can be set in vars/main.yml. For example the kernel role needs a version of the kernel in defaults/main.yml:

kernel_version: 5.0.3

And the rest can be calculated in vars/main.yml:

kernel_unarchive_src: https://cdn.kernel.org/pub/linux/kernel/v.x/linux-.tar.xz

So sometimes set_fact can be used to keep code simple, other (most) times vars/main.yml can help.

For a moral compass Southpark uses Brian Boitano, where my moral coding compass uses Jeff Geerling who would say something like: “If your code is complex, it’s probably not good.”

Different methods to include roles

There are several ways to include roles from playbooks or roles.

Classic

The classic way:

---
- name: Build a machine
  hosts: all
  
  roles:
    - robertdebock.bootstrap
    - robertdebock.java
    - robertdebock.tomcat

Or a variation that allows per-role variables:

---
- name: Build a machine
  hosts: all
  
  roles:
    - role: robertdebock.bootstrap
    - role: robertdebock.java
      vars: java_version: 9
    - role: robertdebock.tomcat

Include role

The include_role way:

---
- name: Build a machine
  hosts: all
  
  tasks:
    - name: include bootstrap
      include_role:
        name: robertdebock.bootstrap

    - name: include java
      include_role:
        name: robertdebock.java

    - name: include tomcat
      include_role:
        name: robertdebock.tomcat

Or a with_items (since Ansible 2.3) variation:

---
- name: Build a machine
  hosts: all
  
  tasks:
    - name: include role
      include_role:
        name: ""
      with_items:
        - robertdebock.bootstrap
        - robertdebock.java
        - robertdebock.tomcat

Sometimes it can be required to call one role from another role. I’d personally use import_role like this:

---
- name: do something
  debug:
    msg: "Some task"

- name: call another role
  import_role:
    name: role.name

If the role (role.name in this example) requires variables, you can set them in vars/main.yml, like so:

variable_x_for_role_name: foo
variable_y_for_role_name: bar

A real life example is my robertdebock.artifactory role calls robertdebock.service role to add a service. The code for the artifactory role contains:

# snippet
- name: create artifactory service
  import_role:
    name: robertdebock.service
# endsnippet

and the variable are set in [vars/main.yml](https://github.com/robertdebock/ansible-role-artifactory/blob/master/vars/main.yml) contains:

service_list:
  - name: artifactory
    description: Start script for Artifactory
    start_command: "/bin/artifactory.sh start"
    stop_command: "/bin/artifactory.sh stop"
    type: forking
    status_pattern: artifactory

A big thanks to … many

My parents, sister and family have been on a holiday to Lanzarote, Spain during christmast and new-year. 11 people in total, 6 adults, 5 children.

During this holiday our oldest got sick. It started as a fever but did not get better, even afer some 2 weeks.

Our oldest is an 8 year old boy, pretty strong and autonomous, no history of sicknesses.

We went to the doctor, he referred us to the hospital in Lanzarote, in Arrecife. He did not get better after receiving antibiotics for some 4 days.

A CT scan indicated his sinuses were infected an the infection broke through to his brains. A medical helicopter was called in to transport him to the hospital on another Canary island; Gran Canaria.

Surgery was performed and he was sent to the “high intensive care”. Quite impressive, but please realize what a horrible time this was for me and my wife.

It’s now 10 days after his surgery, he’s eating, speaking, moving and laughing again. We’ll probably spend this year recovering all of his functions, like walking, properly speaking, etc. I’m hopeful he’ll recover quickly and fully, but what a shock.

TL;DR: Son got sick, he’s doing well, time to code.

All the hospital days and nights gave me quite some time to write code. Because of crappy internet connections, It was a challenge to test code.

Here are the services I’ve used.

I’m very thankful for all the medical staff in Spain, I’m impressed by the quality of the hospital services and staff.

Family, friends and colleagues have expressed their concerns, it does not help my son, but it did help me to know that people are thinking of us.

How to write and maintain many Ansible roles

It’s great to have many code nuggest around to help you setup an environment rapidly. Ansible roles are perfect to describe what you want to do on systems.

As soon as you start to write more roles, you start to develop a style and way of working. Here are the tings I’ve learned managing many roles.

Use a skeleton for stating a new role

When you start to write a new role, you can start with pre-populated code:

ansible-galaxy init --role-skeleton=ansible-role-skeleton role_name

To explain what happens:

Use anible-lint for quick feedback

Andrew has written a tool including many rules that help you write readable and consistent code.

There are times where I don’t agree to the rules, but the feedback is quickly processed.A

There are also times where I initially think rules are useless, but after a while I’m convinced about the intent and change my code.

You can also describe your preferences and use ansible-lint to verify you code. Great for teams that need to agree on a style.

Use molecule on Travis to test

In my opinion the most important part of writing code is testing. I spend a lot of time on writing and executing tests. It helps yourself to prove that certain scenarios work as intended.

Travis can help test your software. A typical commit takes some 30 to 45 minutes to test, but after that I know:

  1. It works on the platforms I want to support.
  2. When it works, the software is released to Galaxy
  3. Pull requests are automatically tested.

It makes me less afraid of committing.

Use versions or tags to release software

When I write some new functionality, I typically need a few iterations to make it work. Using GitHub releases helps me to capture (and release) a working version of a role.

You can play as much as you want in between releases, but when a release is done, the role should work.

Go forth and develop!

You can setup a machine yourself for developing Ansible roles. I’ve prepared a repository that may help.

The playbook in that repository looks something like this:

---
- name: setup an ansible development environment
  hosts: all
  become: yes
  gather_facts: no

  roles:
    - robertdebock.bootstrap
    - robertdebock.update
    - robertdebock.fail2ban
    - robertdebock.openssh
    - robertdebock.digitalocean_agent
    - robertdebock.common
    - robertdebock.users
    - robertdebock.postfix
    - robertdebock.docker
    - robertdebock.investigate
    - robertdebock.ansible
    - robertdebock.ansible_lint
    - robertdebock.buildtools
    - robertdebock.molecule
    - robertdebock.ara
    - robertdebock.ruby
    - robertdebock.travis

  tasks:
    - name: copy private key
      copy:
        src: id_rsa
        dest: /home/robertdb/.ssh/id_rsa
        mode: "0400"
        owner: robertdb
        group: robertdb

    - name: copy git configuration
      copy:
        src: gitconfig
        dest: /home/robertdb/.gitconfig

    - name: create repository_destination
      file:
        path: ""
        state: directory
        owner: robertdb
        group: robertdb

    - name: clone all roles
      git:
        repo: "/.git"
        dest: "/"
        accept_hostkey: yes
        key_file: /home/robertdb/.ssh/id_rsa
      with_items: ""
      become_user: robertdb

When is a role a role

Sometimes it’s not easy to see when Ansible code should be captured in an Ansible role, or when tasks can be used.

Here are some guidelines that help me decide when to choose for writing an Ansible role:

Don’t repeat yourself

When you start to see that your repeating blocks of code, it’s probably time to move those tasks into an Ansible role.

Repeating yourself may:

Keep it simple

Over time Ansible roles tend to get more complex. Jeff Geerling tries to keep Ansible roles under 100 lines. That can be a challenge, but I agree to Jeff.

Whenever I open up somebody else’ Ansible role and the code keeps on scrolling, I tend to get demotivated:

Cleanup your playbook

Another reason to put code in Ansible roles, is to keep your playbook easy to read. A long list of tasks is harder to read than a list of roles.

Take a look at this example:

- name: build the backend server
  hosts: backend
  become: yes
  gather_facts: no

  roles:
    - robertdebock.bootstrap
    - robertdebock.update
    - robertdebock.common
    - robertdebock.python_pip
    - robertdebock.php
    - robertdebock.mysql
    - robertdebock.phpmyadmin

This code is simple to read, anybody could have an understanding what it does.

When input is required

Some roles can have variables to change the installation, imagine this set of variables:

httpd_port: 80

The role can assert variables, for example:

- name: test input
  assert:
    that:
      - httpd_port <= 65535
      - httpd_port >= 1

Check yourself

To verify that you’ve made the right decision:

Could you publish this role?

That means you did not put data in the role, except sane defaults.

Would anybody else be helped with your role?

That means you thought about the interface (defaults/main.yml).

Is there a simple way to test your role?

That means the role is focussed and can do just a few things.

Was it easy to think of the title?

That means you knew what you were building.

Conclusion

Hope this helps you decide when a role is a role.

Testing CVE 2018-19788 with Ansible

So a very simple exploit on polkit has been found. There is not solution so far.

To test if your system is vulnerable, you can run this Ansible role.

A simple playbook that includes a few roles:

---
- name: test cve 2018 19788
  hosts: all
  gather_facts: no
  become: yes

  roles:
    - robertdebock.bootstrap
    - robertdebock.update
    - robertdebock.cve_2018_19788

And a piece of altered-for-readability code from the role:

- name: create a user
  user:
    name: cve_2018_19788
    uid: 2147483659

- name: execute a systemctl command as root
  service:
    name: chronyd
    state: started

In my tests these were the results: (snipped, only kept the interesting part)

TASK [ansible-role-cve_2018_19788 : test if user can manage service] ***********
    ok: [cve-2018-19788-debian] => {
        "changed": false, 
        "msg": "All assertions passed"
    }
    fatal: [cve-2018-19788-ubuntu-16]: FAILED! => {
        "assertion": "not execute_user.changed", 
        "changed": false, 
        "evaluated_to": false, 
        "msg": "users can manage services"
    }
    ...ignoring
    fatal: [cve-2018-19788-ubuntu-18]: FAILED! => {
        "assertion": "not execute_user.changed", 
        "changed": false, 
        "evaluated_to": false, 
        "msg": "users can manage services"
    }
    ...ignoring
    fatal: [cve-2018-19788-ubuntu-17]: FAILED! => {
        "assertion": "not execute_user.changed", 
        "changed": false, 
        "evaluated_to": false, 
        "msg": "users can manage services"
    }
    ...ignoring
    fatal: [cve-2018-19788-fedora]: FAILED! => {
        "assertion": "not execute_user.changed", 
        "changed": false, 
        "evaluated_to": false, 
        "msg": "users can manage services"
    }
    ...ignoring
    fatal: [cve-2018-19788-centos-7]: FAILED! => {
        "assertion": "not execute_user.changed", 
        "changed": false, 
        "evaluated_to": false, 
        "msg": "users can manage services"
    }
    ...ignoring
    ok: [cve-2018-19788-centos-6] => {
        "changed": false, 
        "msg": "All assertions passed"
    }

So for now these distributions seem vulnerable, even after an update:

Ansible on Fedora 30.

Fedora 30 (currenly under development as rawhide) does not have python2-dnf anymore.

The Ansible module dnf tries to install python2-dnf if it running on a python2 environment. It took me quite some time to figure out why this error appeared:

fatal: [bootstrap-fedora-rawhide]: FAILED! => {"attempts": 10, "changed": true, "msg": "non-zero return code", "rc": 1, "stderr": "Error: Unable to find a match\n", "stderr_lines": ["Error: Unable to find a match"], "stdout": "Last metadata expiration check: 0:01:33 ago on Thu Nov 29 20:16:32 2018.\nNo match for argument: python2-dnf\n", "stdout_lines": ["Last metadata expiration check: 0:01:33 ago on Thu Nov 29 20:16:32 2018.", "No match for argument: python2-dnf"]}

(I was not trying to install python2-dnf, so confusion…)

Hm; so I’ve tried these options to work around the problem:

so far the only reasonable option is to set ansible_python_interpreter as documented by Ansible.

provisioner:
  name: ansible
  inventory:
    group_vars:
      all:
        ansible_python_interpreter: /usr/bin/python3

This means all roles that use distributions that:

will need to be modified… Quite a change.

2 December 2018 update: I’ve created pull request 49202 to fix issue 49362.

TL;DR On Fedora 30 (and higher) you have to set ansible_python_interpreter to /usr/bin/python3.

Ansible Molecule testing on EC2

Molecule is great to test Ansible roles, but testing locally with has it’s limitations:

I use my bus-ride time to develop Ansible Roles and the internet connection is limited, which means a lot of waiting. Using AWS EC2 would solve a lot of problems for me.

Here is how to add an EC2 scenario to an existing role.

Save AWS credentials

Edit ~/.aws/credentials using information downloaded from [AWS Console].

[default]
aws_access_key_id=ABC123
aws_secret_access_key=ABC123

Install extra software

On the node where you initiate the tests, a few extra pip modules are required.

pip install boto boto3

Add a scenario

If you already have a role and want to add a single scenario:

cd ansible-role-your-role
molecule init scenario --driver-name ec2 --role-name ansible-role-your-role --scenario-name ec2

Start testing

And simply start testing in a certain region.

export EC2_REGION=eu-central-1
molecule test --scenario-name ec2

The molecule.yml should look something like this:

---
dependency:
  name: galaxy
driver:
  name: ec2
lint:
  name: yamllint
platforms:
  - name: rhel-7
    image: ami-c86c3f23
    instance_type: t2.micro
    vpc_subnet_id: subnet-0e688067
  - name: sles-15
    image: ami-0a1886cf45f944eb1
    instance_type: t2.micro
    vpc_subnet_id: subnet-0e688067
  - name: amazon-linux-2
    image: ami-02ea8f348fa28c108
    instance_type: t2.micro
    vpc_subnet_id: subnet-0e688067
provisioner:
  name: ansible
  lint:
    name: ansible-lint
scenario:
  name: ec2

Weirdness

It feels as if the ec2 driver has had a little less attention as for example the vagrant or docker driver. Here are some strange things:

Molecule and ARA

To test playbooks, molecule is really great. And since Ansible Fest 2018 (Austin, Texas) clearly communicated that Molecule will be a part of Ansible, I guess it’s safe to say that retr0h’s tool will be here to stay.

When testing, it’s even nicer to have great reports. That’s where ARA comes in. ARA collects job output as a callback_plugin, saves it and is able to display it.

Here is how to set it up.

Install molecule

pip install molecule

Install ara

pip install ara

Start ara

ara-manage runserver

Configure molecule to use ara

Edit molecule.yml, under provisioner:

provisioner:
  name: ansible
  config_options:
    defaults:
      callback_plugins: /usr/lib/python2.7/site-packages/ara/plugins/callbacks

Now point your browser to http://localhost:9191/ and run a molecule test:

molecule test

[204] Lines should be no longer than 120 chars

It seems Galaxy is going to use galaxy-lint-rules to star roles. One of the controls tests the length of the lines. Here are a few way so pass those rules.

Spread over lines

In YAML you can use multi line to spread long lines.

Without new lines

The > character replaces newlines by spaces.

- name: demostrate something
  debug: 
    msg: >
      This will just
      be a single long
      line.

With new lines

The | character keeps newlines.

- name: demostrate something
  debug:
    msg: |
      The following lines
      will be spread over
      multiple lines.

Move long lines to vars

Sometimes variables can get very long. You can save a longer variable in a shorter one.

For example, too long would be this task in main.yml:

- name: unarchive zabbix schema
  command: gunzip /usr/share/doc/zabbix-server-{{ zabbix_server_type }}-{{ zabbix_version_major }}.{{ zabbix_version_minor }}/create.sql.gz

Copy-paste that command to vars/main.yml:

gunzip_command: "gunzip /usr/share/doc/zabbix-server-{{ zabbix_server_type }}-{{ zabbix_version_major }}.{{ zabbix_version_minor }}/create.sql.gz"

And change main.yml to simply:

- name: unarchive zabbix schema
  command: "{{ gunzip_command }}"

Conclusion

Yes it’s annoying to have a limitation like this, but it does make the code more readable and it’s not difficult to change your roles to get 5 stars.

Ansible roles for clusters

Ansible can be used to configure clusters. It’s actually quite easy!

Typically a cluster has some master/primary/active node, where stuff needs to be done and other stuff needs to be done on the rest of the nodes.

Ansible can use run_once: yes on a task, which “automatically” selects a primary node. Take this example:

inventory:

host1
host2
host3

tasks/main.yml:

- name: do something on all nodes
  package:
    name: screen
    state: present

- name: select the master/primary/active node
  set_fact:
    master: ""
  run_once: yes

- name: do something to the master only
  command: id
  when:
    - inventory_hostname == master

- name: do something on the rest of the nodes
  command: id
  when:
    - inventory_hostname != master

It’s a simple and understandable solution. You can even tell Ansible that you would like to pin a master:

- name: select the master/primary/active node
  set_fact:
    master: ""
  run_once: yes
  when:
    - master is not defined

In the example above, if you set “master” somewhere, a user can choose to set a master instead of “random” selection.

Hope it helps you!

Ansible Galaxy Lint

Galaxy currently is a dumping place for Ansible roles, anybody can submit any quality role there and it’s kept indefinitly.

For example Nginx is listed 1122 times. Happily Jeff Geerling’s role shows up on top, probably because it has the most downloads.

The Galaxy team has decided that checking for quality is one way to improve search results. It looks liek roles will have a few criterea:

The rules are stored in galaxy-lint-roles. So far Andrew, House and Robert have contributed, feel free to propose new rules or improvements!

You can prepare your roles:

cd directory/to/save/the/rules
git clone https://github.com/ansible/galaxy-lint-rules.git
cd directory/to/your/role
ansible-lint -r directory/to/save/the/rules/galaxy-lint-rules/rules .

I’ve removed quite a few errors by using these rules:

You can peek how your roles are scored on development.

Ansible 2.7

As announced, Ansible 2.7 is out. The changed look good, I’m testing my bootstrap role agains it.

In 2.7 (actually since 2.3) all package modules don’t need with_items: or loop: anymore. This make for simpler code.

- name: customize machine
  hosts: all

  vars:
    packages:
      - bash
      - screen
      - lsof

  tasks:
    - name: install packages
      package:
        name: "{{ packages }}"
        state: present

Wow, that’s simpler so better.

A reboot module has been introduced. Rebooting in Ansible is not easy, so this could make life much simpler.

AnsibleFest2018 (Austin, Texas)

So, it’s been such a good week! Dennis, Marco, Jonathan and I (and 1300 other Ansible fans) visited Ansible Fest 2018.

Good to meet you

After working with quite some people online, I was really happy to finally meet some Ansible heroes:

Highlights

Although nearly each talk was valuable, these are some (randomly ordered) takeaways that influence me:

Difficult to overwrite a single value:

apache:
  start_servers: 2
  max_clients: 2

Easy to overwrite:

apache_start_servers: 2
apache_max_clients: 2

All in all, I’m really happy with the direction Ansible is going and feel that most decicions I’ve done in the past year are correct.

I expect that molecule testing will be integrated into Galaxy and reports will be created using ARA will be integrated.