Cannot send Slack notification via Ansible - ansible

I'm trying to send a Slack notification via Ansible:
- name: Send a custom slack notification
run_once: true
slack:
#s3_backups Slack channel
token: token/stuff/here
attachments:
- text: "S3 Web Server Config Backup Complete."
title: S3 Web Server Backups
color: "#8FCC2C"
delegate_to: localhost
However, I'm getting a fatal error:
TASK [s3_fsn_backend_config_backup : Send a custom slack notification] ********************************************************************************************************************************************
Sorry, try again.
Sorry, try again.
fatal: [webserver-name -> localhost]: FAILED! => {"changed": false, "module_stderr": "[sudo via ansible, key=blahblahblahblahblah] password:[sudo via ansible, key=blahblahblahblahblah] password:sudo: 3 incorrect password attempts\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
Am I using incorrect syntax? I just want it to run from localhost. I definitely don't understand what the Sorry, try again message means.

You can try the following code snippet
- name: Send slack notifications
slack:
token: "{{ slack_token }}"
msg: "Hello World"
channel: "#general"
username: "Ansible"
icon_url: "https://www.ansible.com/favicon.ico"
link_names: 1
parse: "full"
color: "#00ff00"
attachments:
- text: "This is an attachment"
color: "#ff0000"
fields:
- title: "Field 1"
value: "This is an attachment"
short: false
- title: "Field 2"
value: "This is an attachment"
short: false
footer: "Footer"
footer_icon: "https://www.ansible.com/favicon.ico"
ts: 123456789
More details available at slack_module

Related

Ansible - #CLIXML error on a windows host

I have an issue when I run my playbook.yaml with -vvvv during Gathering Facts. I have the following error message :
fatal: [HOST.DOMAIN.COM]: FAILED! => {
"ansible_facts": {},
"changed": false,
"failed_modules": {
"ansible.legacy.setup": {
"failed": true,
"module_stderr": "#< CLIXML\r\n",
"module_stdout": "",
"msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
"rc": 1
}
},
"msg": "The following modules failed to execute: ansible.legacy.setup\n"
I search on internet and I try different things like change the size of max memory per shell but it changes nothing.
Do you know how to resolve it or a way that i can explore for solve it pls ? If I need to change my config ?
Playbook.yaml :
- name: Who am I
hosts: win
tasks:
- name: Check my user name
ansible.windows.win_whoami:
win.yaml (variables) :
ansible_user: admin#DOMAIN.COM
ansible_password: Password
ansible_connection: winrm
ansible_winrm_transport: kerberos
ansible_winrm_server_cert_validation: ignore
ansible_winrm_port: 5986
My Windows host :
OS : Microsoft Windows Server 2016 Standard
Powershell Version : 5.1.14393.5127

Ansible uri with faild_when and loop fails

I have a problem with a loop and failed_with in ansible. I don't know why.
The actual failed_when is much more complex, I know i could use status_code in this case.
It is my goal to parse the json response from a local api for multiple (dynamic list I got early from the api) objects and fail if it is not a response I expect.
- name: "get status for items"
uri:
url: https://{{inventory_hostname}}/status
method: POST
body_format: json
body: "{'index': {{item.index}}"
register: this
failed_when: "this.status != 200"
loop: "{{ item_list.json | json_query('[?state== `UNDEFINED`]') }}"
I get the error:
fatal: [localhost]: FAILED! =>
msg: |-
The task includes an option with an undefined variable. The error was: 'this' is undefined
The error appears to be in '/home/blablup/Devel/ansible/roles/myrole/tasks/update.yml': line 48, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: "get status for items"
^ here
But if I read the documentation it should work this way. Also if I look at this: Using `failed_when` on a `with_items` task depending on return codes example, failed_when should be evaluated for every iteration.
I am unable to reproduce the behavior you've described. If I wrap your task in sufficient code to run it, like this:
- hosts: localhost
gather_facts: false
vars:
item_list:
json:
- state: UNDEFINED
index: 0
- state: okay
index: 1
- state: UNDEFINED
index: 2
tasks:
- name: "get status for items"
uri:
url: http://localhost:5000/status
method: POST
body_format: json
body: "{'index': {{item.index}}"
register: this
failed_when: "this.status != 200"
loop: "{{ item_list.json | json_query('[?state== `UNDEFINED`]') }}"
And provide a server that will return either a 200 or a 400 response:
from flask import Flask, request, make_response
app = Flask(__name__)
#app.route("/status", methods=["POST"])
def status():
if b"2" in request.data:
return make_response("failed", 400)
else:
return make_response("okay", 200)
Then running your playbook produces the expected behavior (it succeeds when the server delivers a 200 response, and fails when the server returns a non-200 response):
TASK [get status for items] *****************************************************************************
ok: [localhost] => (item={'name': 'foo', 'state': 'UNDEFINED', 'index': 0})
failed: [localhost] (item={'name': 'qux', 'state': 'UNDEFINED', 'index': 2}) => {"ansible_loop_var": "item", "changed": false, "connection": "close", "content_length": "6", "content_type": "text/html; charset=utf-8", "date": "Wed, 12 Oct 2022 00:10:05 GMT", "elapsed": 0, "failed_when_result": true, "item": {"index": 2, "name": "qux", "state": "UNDEFINED"}, "msg": "Status code was 400 and not [200]: HTTP Error 400: BAD REQUEST", "redirected": false, "server": "Werkzeug/2.2.2 Python/3.10.7", "status": 400, "url": "http://localhost:5000/status"}
I'm using Ansible core version 2.12.6.
Unrelated to your question, but this looks suspicious:
body: "{'index': {{item.index}}"
You're not delivering a JSON request body (JSON does not use single quotes and your brackets aren't balanced). You want something like this:
body: {
"index": "{{ item.index }}"
}

Conditional when win_service exists?

I'm creating playbook to install fluentbit on windows hosts. Everything is working properly but i'm getting error when creating service, it doesn’t fail the install as then everything is already in place but I would like to figure out how I could leverage conditionals. Could you help me with this? :)
My adhoc test-play where I've tried to parse results from ansible.windows.win_service_info module is as follows:
---
- name: Check Windows service status
hosts: win
gather_facts: True
tasks:
- name: Check if a service is installed
win_service:
name: fluent-bit
register: service_info
- debug: msg="{{service_info}}"
- name: Get info for a single service
ansible.windows.win_service_info:
name: fluent-bit
register: service_info
- debug: msg="{{ service_info }}"
- name: Get info for a fluent-bit service
ansible.windows.win_service_info:
name: logging
register: service_exists
- debug: msg="{{ service_exists }}"
- name: Send message if service exists
debug:
msg: "Service is installed"
when: service_exists.state is not defined or service_exists.name is not defined
- name: Send message if service exists
debug:
msg: "Service is NOT installed"
when: service_exists.state is not running
I just don’t get it how I could parse output so that I could skip task when fluent-bit -service exists = True like here:
TASK [debug] *****************************************************************************************
ok: [win-server-1] => {
"msg": {
"can_pause_and_continue": false,
"changed": false,
"depended_by": [],
"dependencies": [],
"description": "",
"desktop_interact": false,
"display_name": "fluent-bit",
**"exists": true,**
"failed": false,
"name": "fluent-bit",
"path": "C:\\fluent-bit\\bin\\fluent-bit.exe -c C:\\fluent-bit\\conf\\fluent-bit.conf",
"start_mode": "manual",
"state": "stopped",
"username": "LocalSystem"
}
}
Cheers :)
So, got it working as I wanted with service_info.exists != True, now it will skip the task if service is already present.

ansible - cant set wallpaper in xfce4 with xfconf "failed to init libxfconf "

I try to set a wallpaper on Debian Systems with ansible on xfce4 desktops. For this I looked up the official documentation: https://docs.ansible.com/ansible/latest/collections/community/general/xfconf_module.html
My Task:
- name: set wallpaper
become_user: odin
xfconf:
channel: "xfce4-desktop"
property: "/backdrop/screen0/{{item}}/image-path"
value_type: "string"
value: ['/usr/share/backgrounds/xfce/802192.jpg']
loop:
- monitor0
- monitor1
- monitorDP-1
- monitoreDP-1
I receive the following error:
XFConfException: xfconf-query failed with error (rc=1): Failed to init libxfconf: Error spawning command line “dbus-launch --autolaunch=2e66f568a1c34fda92dcec58e724b679 --binary-syntax --close-stderr”: Child process exited with code 1.
failed: [localhost] (item=monitoreDP-1) => {
"ansible_loop_var": "item",
"changed": false,
"invocation": {
"module_args": {
"channel": "xfce4-desktop",
"force_array": false,
"property": "/backdrop/screen0/monitoreDP-1/image-path",
"state": "present",
"value": [
"/usr/share/backgrounds/xfce/802192.jpg"
],
"value_type": [
"string"
]
}
},
"item": "monitoreDP-1",
"msg": "Module failed with exception: xfconf-query failed with error (rc=1): Failed to init libxfconf: Error spawning command line “dbus-launch --autolaunch=2e66f568a1c34fda92dcec58e724b679 --binary-syntax --close-stderr”: Child process exited with code 1.",
"output": {
"ansible_facts": {
"xfconf": {}
},
"cmd_args": [
"/usr/bin/xfconf-query",
"--channel",
"xfce4-desktop",
"--property",
"/backdrop/screen0/monitoreDP-1/image-path"
],
"force_lang": "C",
"rc": 1,
"stderr": "Failed to init libxfconf: Error spawning command line “dbus-launch --autolaunch=2e66f568a1c34fda92dcec58e724b679 --binary-syntax --close-stderr”: Child process exited with code 1.\n",
"stdout": ""
},
"vars": {
"cmd_args": [
"/usr/bin/xfconf-query",
"--channel",
"xfce4-desktop",
"--property",
"/backdrop/screen0/monitoreDP-1/image-path"
]
}
}
I thought about copying the xml config for xfce4-desktop on to every machine, but not every machine has the same screen "monitor" property.
Got it to work. Seems like running the task as root was doing the trick.
The xfce modification works as root for me as well with the following approach:
- name: Copy wallpaper file
copy:
src: files/wallpaper.jpg
dest: /usr/share/backgrounds/xfce/debian-wallpaper.jpg
owner: root
group: root
when: ansible_distribution == "Debian"
- name: Change wallpaper
become: true
xfconf:
channel: xfce4-desktop
property: /backdrop/screen0/monitoreDP-1/workspace0/last-image
value: ["/usr/share/backgrounds/xfce/debian-wallpaper.jpg"]
value_type: string
when: ansible_distribution == "Debian"
This will configure the xfce files in /root/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-desktop.xml though.
I was not able to do it for another user USERNAME, besides with this workaround:
- name: Copy xfce4 desktop xml files from root to user
copy:
src: /root/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-desktop.xml
dest: /home/USERNAME/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-desktop.xml
owner: USERNAME
group: USERNAME
force: yes
when: ansible_distribution == "Debian"
If anybody know how to use xfconf module in a better way to overcome this workaround, please let me know.

Create influxdb user using Ansible

How can I create a user in Influxdb using ansible module ?
In influxdb ansible docs , I could not find that how to create a user.
I am trying to create it via influxdb API, but have not got success in that.
- name: create user in influxdb
uri:
url: "http://localhost:8086/query"
method: POST
body: "--data-urlencode 'q=CREATE USER myuser WITH PASSWORD 'mypass' WITH ALL PRIVILEGES'"
body_format: raw
The response is,
fatal: [192.168.122.62]: FAILED! => {"changed": false, "connection": "close", "content": "{\"error\":\"missing required parameter \\\"q\\\"\"}\n", "content_length": "45", "content_type": "application/json", "date": "Wed, 05 Jul 2017 12:08:26 GMT", "failed": true, "json": {"error": "missing required parameter \"q\""}, "msg": "Status code was not [200]: HTTP Error 400: Bad Request", "redirected": false, "request_id": "a6c36bfd-617a-11e7-800c-000000000000", "status": 400, "url": "http://localhost:8086/query", "x_influxdb_version": "1.2.2"}
I had a nightmare with quotes... BUT this one worked for me:
- name: "[Centos7_InfluxDB] Create InfluxDB user"
command: 'influx -database {{item.database}} -execute "CREATE USER {{item.user}} WITH PASSWORD
{{item.pass}} WITH ALL PRIVILEGES"'
with_items:
- { database: "sample_database", user: "adminuser", pass: "'adminpass'" }
This code should work as you expect :
- name: create user in influxdb
uri:
url: "http://localhost:8086/query"
method: POST
body: "q=CREATE USER myuser WITH PASSWORD 'mypass' WITH ALL PRIVILEGES"
You can easily create a user using the command module.
- name: Create InfluxDB user
command: "influx -execute \"CREATE USER {{item.user}} WITH PASSWORD
'{{item.pass}}' WITH ALL PRIVILEGES\""
with_items:
- { user: 'admin', pass: 'admin' }
This should be a lot more efficient than using the REST api.
If anyone's wondering about that as well - just keep in mind that there are community modules for Ansible that already do everything you want, without having to do it with raw/command modules

Resources