dude0786
dude0786

Reputation: 61

Ansible: Trigger the task only when previous task is successful and the output is created

I am deploying a VM in azure using ansible and using the public ip created in the next tasks. But the time taken to create the public ip is too long so when the subsequent task is executed, it fails. The time to create the ip also varies, it's not fixed. I want to introduce some logic where the next task will only run when the ip is created.

- name: Deploy Master Node
  azure_rm_virtualmachine:
    resource_group: myResourceGroup
    name: testvm10
    admin_username: chouseknecht
    admin_password: <your password here>
    image:
      offer: CentOS-CI
      publisher: OpenLogic
      sku: '7-CI'
      version: latest

Can someone assist me here..! It's greatly appreciated.

Upvotes: 1

Views: 2262

Answers (1)

larsks
larsks

Reputation: 312138

I think the wait_for module is a bad choice because while it can test for port availability it will often give you false positives because the port is open before the service is actually ready to accept connections.

Fortunately, the wait_for_connection module was designed for exactly the situation you are describing: it will wait until Ansible is able to successfully connect to your target.

This generally requires that you register your Azure VM with your Ansible inventory (e.g. using the add_host module). I don't use Azure, but if I were doing this with OpenStack I might write something like this:

- hosts: localhost
  gather_facts: false
  tasks:
    # This is the task that creates the vm, much like your existing task
    - os_server:
        name: larstest
        cloud: kaizen-lars
        image: 669142a3-fbda-4a83-bce8-e09371660e2c
        key_name: default
        flavor: m1.small
        security_groups: allow_ssh
        nics:
          - net-name: test_net0
        auto_ip: true
      register: myserver

    # Now we take the public ip from the previous task and use it
    # to create a new inventory entry for a host named "myserver".
    - add_host:
        name: myserver
        ansible_host: "{{ myserver.openstack.accessIPv4 }}"
        ansible_user: centos

# Now we wait for the host to finished booting. We need gather_facts: false here
# because otherwise Ansible will attempt to run the `setup` module on the target,
# which will fail if the host isn't ready yet.
- hosts: myserver
  gather_facts: false
  tasks:
    - wait_for_connection:
        delay: 10

# We could add additional tasks to the previous play, but we can also start
# new play with implicit fact gathering.
- hosts: myserver
  tasks:
    - ...other tasks here...

Upvotes: 2

Related Questions