Using ansible to post MS Teams messages

Feb 2, 2020 ansible ms teams api

In this post i'll show you one way you can interact with Microsoft Teams (or any API) in your ansible playbooks. The idea behind doing this was initially to provide a simple way to log progress from the command line, seeing as thats where they already spend a lot of time, but obviously there are many use cases for something like this. Maybe you want your playbook to interact with other messaging APIs while it runs, or send progress updates to other team members etc.

To set this up, you need a Microsoft Team, the uri ansible module and a bit of creativity.

First up create a new Role, i called mine “teams-chttr”, because i just want to send lines to Teams. Create the following directory and file structure.

roles/lines
├── defaults
│   └── main.yml
├── tasks
│   └── main.yml
└── templates
    └── message.j2

3 directories, 3 files

roles/lines/defaults/main.yml holds default variables for the role. We will create a message variable to store message we post to Teams, as well a webhook variable to store our Teams webhook url here. The message variable does a lookup and grabs the contents of our message.j2 template file.

---
message: "{{ lookup('template', 'message.j2') }}"
webhook: 'https://outlook.office.com/webhook/your_webhook_url'

roles/lines/templates/message.j2 holds the specific JSON message structure required by MS Teams, used as the body we POST to the webhook. The text string is the important bit, you can format that however you wish. You can even go and create advanced and interactive Teams Message cards, play here https://amdesigner.azurewebsites.net/. In the text string i have included the current datetime, the current user and additional text they may wish to supply from the command line. Note: the {{ l }} variable is supplied on the command line, you can simply remove this if you don't need/want it.

{
    "type": "AdaptiveCard",
    "text": "{{ ansible_date_time.date }}: ({{ ansible_user_id }}) {{ l }}"
}

roles/lines/tasks/main.yml contains the ansible task to post to Teams. We are using the built in uri module, you can see details of how to use it here https://docs.ansible.com/ansible/latest/modules/uri_module.html. We are using the webook and message variables we defined in defaul/main.yml.

---
# This role logs a line to MS Teams
- name: Log lines to MS Teams
  uri:
    url: "{{ webhook }}"
    body: "{{ message }}"
    body_format: json
    method: POST

Now simply include this Role in your playbook and you can execute it from the comand line like this.

ansible-playbook msteams.yml -e "l='foo bar bang'"

You should see a message like this appear in Teams.

ansible-teams-api-message

You can get the Role and full source code here https://github.com/adrwh/ansible-role-teams-chttr