Strane race condition in Ansible

Hello!

I've found a weird issue, which makes a playbook fail 'sometimes' in a
way that's entirely related to the local Ansible code. It looks like
this:

          ...
        
          tasks:
            - name: get a unique ID for an EC2 cluster
              local_action: >
                command date "+%N"
              register: timestamp

            - name: launch ec2 instances
              local_action: >
                ec2 key_name={{ ssh_key_name }}
                    group={{ security_group }}
                    instance_type={{ instance_type }}
                    image={{ image }}
                    region={{ region }}
                    count={{ num_hosts }}
                    wait=true
                    instance_tags='{ "cluster_id" : {{ timestamp.stdout }} }'
              register: ec2results
        
          ...
        
Have a look at the "instance_tags". As you can see here, I would like to
tag all EC2 hosts with a 'cluster_id' key, which consists of a
timestamp. Ever now and then, maybe 50% of the time, when I run this
playbook, I get this error here:

        PLAY [create the cluster hosts] ***********************************************
        
        TASK: [get unique ID for cluster] *********************************************
        changed: [localhost]
        
        TASK: [launch ec2 instances] **************************************************
        failed: [localhost] => {"failed": true}
        msg: unable to evaluate dictionary for instance_tags
        
        FATAL: all hosts have already failed -- aborting
        
I can start the playbook immediately again, and usually, it works just
fine then. It's almost as if sometimes the timestamp doesn't really
become immediately available, or some similar issue.

Is there any reason for this? Am I doing something wrong? Should this
not work as I'm expecting?

Juergen

Those two steps are in fact executed one before each other so you shouldn’t see any race condition behavior.

However, this value is in fact JSON, as you have it, so I’m wondering if you’re occasionally getting a parse error based on what the time is, due to a lack of quoting.

The better way to use this module is like so:

ec2_key:
key_name: “{{ ssh_key_name }}”

all of the arguments here…

instance_tags:
cluster_id: “{{ timestamp.stdout }}”

Which may help. I’d try it and see.

Using the complex arguments form eliminates the need to have the JSON string.

Hello,
I am experiencing exactly the same problem with ec2 tags.

I can easily set them up but following steps fails.
If I simply re run the playbook it just works…