0 API & automation
Sameer Gautam edited this page 2018-04-11 20:22:14 +05:45

API & automation

...to run semaphore task-templates from cronjobs, jenkins, etc.

to run a task-template you need it's ID

You can get Template ID from Update Template dialog (if you use latest semaphore version). More documentation about Semaphore API here - https://ansible-semaphore.github.io/semaphore/

calling the api from the commandline with curl

# login to the semaphore (password should be escaped, "slashy\\pass" instead of "slashy\pass" e.g.)
curl --cookie-jar /tmp/semaphore-cookie -X POST --header 'Content-Type: application/json' --header 'Accept: application/json'  -d '{"auth": "semaphore_user","password": "semaphore_password"}' https://ansible.yourdomain.com/api/auth/login -v
#204 Response code should be returned

# get user tokens
curl -b /tmp/semaphore-cookie https://ansible.yourdomain.com/api/user/tokens -v
# If user has no tokens, empty array will be returned

#generate a new token if user had no one
curl -b /tmp/semaphore-cookie -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' https://ansible.yourdomain.com/api/user/tokens -v
#201 Response code should be returned

# get user tokens again
curl -b /tmp/semaphore-cookie https://ansible.yourdomain.com/api/user/tokens -v
#Should be returned something like:
#[{"id":"long_random_token_string","created":"2017-03-11T13:13:13Z","expired":false,"user_id":1}]

# use this token for launching a task or anything else
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'Authorization: Bearer long_random_token_string' -d '{"template_id": 1, "debug": false, "dry_run": false, "playbook": "", "environment": ""}' https://ansible.yourdomain.com/api/project/1/tasks -v

#alternatively you still may use cookie
curl -X POST -b /tmp/semaphore-cookie --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{"template_id": 1, "debug": false, "dry_run": false, "playbook": "", "environment": ""}' https://ansible.yourdomain.com/api/project/1/tasks -v

(copied from https://github.com/ansible-semaphore/semaphore/issues/184#issuecomment-285866357)