Jan 21

Using Ansible like library programming in Python

Reading time: 2 – 4 minutes

Ansible is a very powerful tool. Using playbooks, something like a cookbook, is very easy to automate maintenance tasks of systems. I used Puppet and other tools like that but IMHO Ansible is the best one.

In some cases you need to manage dynamic systems and take into advantage of Ansible like a Python library is a very good complement for your scripts. This is my last requirement and because of that I decided to share some simple Python snippets that help you to understand how to use Ansible as a Python library.

Firstly an example about how to call an Ansible module with just one host in the inventory (test_modules.py):

import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils
import json

# the fastest way to set up the inventory

# hosts list
hosts = [""]
# set up the inventory, if no group is defined then 'all' group is used by default
example_inventory = ansible.inventory.Inventory(hosts)

pm = ansible.runner.Runner(
    module_name = 'command',
    module_args = 'uname -a',
    timeout = 5,
    inventory = example_inventory,
    subset = 'all' # name of the hosts group 

out = pm.run()

print json.dumps(out, sort_keys=True, indent=4, separators=(',', ': '))

As a second example, we’re going to use a simple Ansible Playbook with that code (test.yml):

- hosts: sample_group_name
    - name: just an uname
      command: uname -a

The Python code which uses that playbook is (test_playbook.py):

import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils
import json

### setting up the inventory

## first of all, set up a host (or more)
example_host = ansible.inventory.host.Host(
    name = '',
    port = 22
# with its variables to modify the playbook
example_host.set_variable( 'var', 'foo')

## secondly set up the group where the host(s) has to be added
example_group = ansible.inventory.group.Group(
    name = 'sample_group_name'

## the last step is set up the invetory itself
example_inventory = ansible.inventory.Inventory()

# setting callbacks
stats = callbacks.AggregateStats()
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)

# creating the playbook instance to run, based on "test.yml" file
pb = ansible.playbook.PlayBook(
    playbook = "test.yml",
    stats = stats,
    callbacks = playbook_cb,
    runner_callbacks = runner_cb,
    inventory = example_inventory,

# running the playbook
pr = pb.run()  

# print the summary of results for each host
print json.dumps(pr, sort_keys=True, indent=4, separators=(',', ': '))

If you want to download example files you can go to my github account: github.com/oriolrius/programming-ansible-basics

I hope it was useful for you.

Dec 01

Short MIIMETIQ definition

Reading time: 2 – 3 minutes


Last months in M2M Cloud Factory we have been working on MIIMETIQ. Last weeks I’ve been thinking about how to define MIIMETIQ shortly and this is my definition, please tell if you can understand something. Of course, you have to know we’re focused in Internet of Things and M2M market.

  • MIIMETIQ is an IoT/M2M framework, so this is the first step to setup to develop your vertical solution.
  • Framework: With a well defined architecture a framework is a set of functions ready to create any application. Everything else is open and adaptable.
  • MIIMETIQ architecture is service oriented and it uses AMQP as a message broker to connect the services.
  • MIIMETIQ has several modules, we define a module as a set of services. Basicly MIIMETIQ have 5 modules:
    • Identity Manager: manage users, groups, roles and all kind of entities the project needs and its security.
    • Assets Manager: a data model manager, the integrator creates the business logics and data models here.
    • Distribution System: this is a set of agnostitc connectivity layers to different types of devices.
    • A E N M: several time series and other signals flow through the AMQP, this data are events and using rules those events could be converted in alarms and some alarms have to be notified to proper services, systems or people.
    • Control Panel UI: this is an administration dashboard, in form of a UI to setup and monitor the most common uses of MIIMETIQ.
  • Using those modules usually the integrators create their own user interface to satisfy customer requiremests. In M2MCF we create those UI using ADUX (Advanced Development User Experience).
  • After configuring MIIMETIQ the integrator has 2 customized APIs to connect their code with MIIMETIQ. One of them is an API REST and another one is AMQP.
  • Finally everything inside MIIMETIQ could be customized, because the flexibility is very important when you have an horizontal solution.
Oct 21

OpenAM: some ssoadm commands for reference

Reading time: 3 – 4 minutes

OpenAM is as much powerful as complicated sometimes. In this case I spent a lot of time understanding how to set simple settings because of that I decide to take note about that in this blog entry.

First of all don’t forget to set the environment variables and go to ssoadm path:

export JAVA_HOME="/usr/lib/jvm/java-6-openjdk-amd64/jre"
export CLASSPATH="/var/lib/tomcat7/webapps/openam/WEB-INF/lib/policy-plugins.jar::/var/lib/tomcat7/webapps/openam/WEB-INF/lib/openam-core-11.0.0.jar"

cd /opt/openam/ssoadmin/openam/bin

Getting the list of user identities:

./ssoadm list-identities -u amadmin -f /tmp/oam.pwd -e / -t User -x "*"

anonymous (id=anonymous,ou=user,dc=openam)
demo (id=demo,ou=user,dc=openam)
serviceusername (id=serviceusername,ou=user,dc=openam)
amAdmin (id=amAdmin,ou=user,dc=openam)
Search of Identities of type User in realm, / succeeded.

another useful query would be:

./ssoadm list-identities -u amadmin -f /tmp/oam.pwd -e / -t Role -x "*"

No plug-ins configured for this operation

But as you can see it doesn’t work and I don’t know how to solve it.

Taking a look to GUI get to identities list with: Access Control > / (Top Level Realm) > Privileges

In this webpage you have a list of role identities, in my case I have only this: “All Authenticated Users”. Inside this identity I can set different privileges:

  • REST calls for Policy Evaluation (EntitlementRestAccess)
  • Read and write access to all log files (LogAdmin)
  • REST calls for searching entitlements (PrivilegeRestReadAccess)
  • Read access to all log files (LogRead)
  • Read and write access to all federation metadata configurations (FederationAdmin)
  • Read and write access only for policy properties (PolicyAdmin)
  • Read and write access to all configured Agents (AgentAdmin)
  • Read and write access to all realm and policy properties (RealmAdmin)
  • REST calls for managing entitlements (PrivilegeRestAccess)
  • Write access to all log files (LogWrite)

If we want to remove a privilege:

root@vm:/opt/openam/ssoadmin/openam/bin# ./ssoadm remove-privileges -u amAdmin -f /tmp/oam.pwd -e / -g EntitlementRestAccess -i "All Authenticated Users" -t role

Privileges were removed from identity, All Authenticated Users of type, role in realm, /.

or adding a privilege:

root@vm:/opt/openam/ssoadmin/openam/bin# ./ssoadm add-privileges -u amAdmin -f /tmp/oam.pwd -e / -g EntitlementRestAccess -i "All Authenticated Users" -t role

Talking about policies, exporting:

./ssoadm list-policies -u amadmin -f /tmp/oam.pwd -e / -o /tmp/policies.xml

and if we want to import the policies:

./ssoadm create-policies -u amAdmin -f /tmp/oam.pwd -e / --xmlfile /tmp/policies.xml

creating a user:

./ssoadm create-identity -u amadmin -f /tmp/oam.pwd  -e / -i serviceusername -t User --attributevalues "userpassword=servicepassword"

Useful references:

Jul 08

sslsnoop – hacking OpenSSH

Reading time: < 1 minute

Using sslsnoop you can dump SSH keys used in a session and decode ciphered traffic. Supported algorithms are: aes128-ctr, aes192-ctr, aes256-ctr, blowfish-cbc, cast128-cbc.

Basic sslsnoop information:

 $ sudo sslsnoop # try ssh, sshd and ssh-agent… for various things
 $ sudo sslsnoop-openssh live `pgrep ssh` # dumps SSH decrypted traffic in outputs/
 $ sudo sslsnoop-openssh offline –help # dumps SSH decrypted traffic in outputs/ from a pcap file
 $ sudo sslsnoop-openssl `pgrep ssh-agent` # dumps RSA and DSA keys

Take a look into the project in sslsnoop github page.

Jun 30

Enabling linux kernel to open LOTS of concurrent connections

Reading time: < 1 minute

Just a small recipe about how to enable linux kernel to open tons of concurrent connections. Really simple and useful post entry.

echo “10152 65535″ > /proc/sys/net/ipv4/ip_local_port_range
sysctl -w fs.file-max=128000
sysctl -w net.ipv4.tcp_keepalive_time=300
sysctl -w net.core.somaxconn=250000
sysctl -w net.ipv4.tcp_max_syn_backlog=2500
sysctl -w net.core.netdev_max_backlog=2500
ulimit -n 10240
Jan 24

Conferència: La revolució dels mini-PC: Raspberry PI, Arduino i més

Reading time: 1 – 2 minutes

Ahir al vespre vaig fer una conferència a la FIB (Facultat d’Informàtica de Barcelona) dins de la UPC (Universitat Politècnica de Catalunya). En aquesta xerra vaig estar explicant què és i en que es diferència Arduino i Raspberry PI. A més de presentar tot un conjunt de solucions alternatives i experiències en el tema.

En aquest enllaç podeu trobar les transparències de:  La revolució dels mini-PC: Raspberry PI, Arduino i més. i el video el teniu disponible al servidor de la FIB.

Ara també teniu disponible el video a youtube:

i podeu veure les transparències des d’aquest mateix post:

Espero els vostres feedbacks als comentaris, desitjo que ús sigui útil.