Home Using Ansible Semaphore with Home assistant
Post
Cancel

Using Ansible Semaphore with Home assistant

On the journey to control all my home with automation I wanted to start using ansible with Home Assistant. As my Home Assistant instance is on 24/7 I made sense.

The easiest way I could think of using ansible with Home Assistant was to use the built in Rest API from Ansible Semaphore.

Once you’ve got Semaphore up and running with the templates you can call the API.

The one thing to remember is to get the Template ID correct. The way I understand it is the count of the templates in the WebGUI is going to be the number you use.

Template count

Home Assistant files

You’ll need to create a bash script file to call the REST API. Here is an example of the bash script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/bash
# change the changeme to your username and password for ansible-semaphore
curl -v -c /tmp/semaphore-cookie -X 'POST' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{"auth": "changeme", "password": "changeme"}' \
http://<IPADDRESS-OF-ANSIBLE-SEMAPHORE>:3000/api/auth/login

curl -v -b /tmp/semaphore-cookie \
-H 'accept: application/json' \
http://<IPADDRESS-OF-ANSIBLE-SEMAPHORE>:3000/api/project/1/


curl -v -b /tmp/semaphore-cookie -X 'POST' \
'http://<IPADDRESS-OF-ANSIBLE-SEMAPHORE>:3000/api/project/1/tasks' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"template_id": 2,
"debug": false,
"dry_run": false,
"playbook": "shutdown-windows.yml",
"environment": "{}"
}'

Pay attention to this, the template ID is the count of the task you want to run and the playbook corresponds with that template ID

1
2
3
4
5
6
7
'{
"template_id": 2,
"debug": false,
"dry_run": false,
"playbook": "shutdown-windows.yml",
"environment": "{}"
}'

Using the Bash script with Home assistant

Put the bash script in a folder inside the config directory of Home Assistant. I’ve put mine in ansible-scipts

Put this in the configuration.yaml in home assistant

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# This section creates a switch that you can use to run the Rest Bash script
switch:
  - platform: template
    switches:
      off_ansible:
        turn_off:
          service: shell_command.windows_shutdown
        turn_on:
          service: notify.mobile_app_pixel_6
          data:
            message: test
            title: test

# This section creates key and value to use the shell script
shell_command:
  windows_shutdown: bash /config/ansible-scripts/shutdown-pc.sh

Now once Home Assistant is restarted you should be able to use a switch to call the REST API script to call the ansible task.

Example of Home Assistant files

Template count

This post is licensed under CC BY 4.0 by the author.
Trending Tags