Only run Ansible task on box in specific group - ansible

I am trying to create a task that will only run on a box that is in a specific group (called pi).
I am using Ansible version:
ansible 2.3.2.0
config file = /Users/user/Development/raspbian-homeassistant/ansible.cfg
configured module search path = Default w/o overrides
python version = 3.6.3 (default, Dec 3 2017, 10:37:53) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.38)]
This is my current code:
- name: Set up zwave USB dongle
when: inventory_hostname in groups['pi']
blockinfile:
path: /var/local/homeassistant/.homeassistant/configuration.yaml
marker: "# {mark} ANSIBLE MANAGED BLOCK #"
insertafter: "# zwave dongle"
content: |2
zwave:
usb_path: /dev/ttyACM0
tags:
- config
- hass
It seems to work correctly when the hostname is in the group but throws an error when not.
This is the error I get when I run it on my vagrant box (in group vagrant):
fatal: [192.168.33.123]: FAILED! => {"failed": true, "msg": "The conditional check 'inventory_hostname in groups['pi']' failed. The error was: error while evaluating conditional (inventory_hostname in groups['pi']): Unable to look up a name or access an attribute in template string ({% if inventory_hostname in groups['pi'] %} True {% else %} False {% endif %}).\nMake sure your variable name does not contain invalid characters like '-': argument of type 'StrictUndefined' is not iterable\n\nThe error appears to have been in '/Users/andy/Development/raspbian-homeassistant/ansible/roles/configure-hass/tasks/main.yml': line 21, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Set up zwave USB dongle\n ^ here\n"}
Check if a list contains an item in Ansible suggests I have the syntax right but I guess that is for an older version of Ansible?
How do I fix this?

Generally, if you want tasks to apply only to hosts in a particular group, the way you do that is by creating a play that targets that group:
- hosts: pi
tasks:
- name: Set up zwave USB dongle
blockinfile:
path: /var/local/homeassistant/.homeassistant/configuration.yaml
marker: "# {mark} ANSIBLE MANAGED BLOCK #"
insertafter: "# zwave dongle"
content: |2
zwave:
usb_path: /dev/ttyACM0
tags:
- config
- hass
The error you're getting is because groups['pi']is undefined. There are a couple of ways of preventing the error. For example, you can explicitly check thatgroups['pi']` is defined before trying to use it:
- name: set up zwave USB dongle
when: groups['pi'] is defined and inventory_hostname in groups['pi']
Or you can use the default filter to provide a default value:
- name: set up zwave USB dongle
when: inventory_hostname in groups['pi']|default([])

Related

Ansible with no action detected in task

I would like to check TLS/SSL certificate expiration date from Ansible.
After execute a valid YML (ansible-playbook TEST.yml) appears the following error:
ERROR! no action detected in task. This often indicates a misspelled module name, or incorrect module path.
The error appears to have been in '/scripts/Ansible/TEST.yml': line 15, column 7, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: check validity
^ here
This is the code:
- name: find cerfication files & expiration dates
hosts: 10.0.1.41
gather_facts: false
tasks:
- name: Find cert files under /etc/pki/tls/certs
find:
paths: /etc/pki/tls/certs
file_type: file
patterns: "*.crt"
recurse: yes
excludes: "localhost.crt"
register: find_result
- name: check validity
openssl_certificate_info:
path: "{{ item.path }}"
valid_at:
point_1: "+1w"
point_2: "+10w"
register: result
loop: "{{ find_result.files|flatten(levels=1) }}"
- debug: msg= "{{ result }}"
What's the exactly wrong?
My version:
[root#ansible Ansible]# ansible-playbook --version
ansible-playbook 2.6.20
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.6/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.6.6 (r266:84292, Jun 20 2019, 14:14:55) [GCC 4.4.7 20120313 (Red Hat 4.4.7-23)]
You are on a really old version of Ansible, I would recommend you to upgrade since your version had an end of support long ago (November 6, 2019).
Now, the module you are trying to use didn't exist in the version 2.6, that's the reason for the error raised by Ansible.
In the version 2.6, the way to check a certificate was to use the openssl_certificate module.
Something like:
- name: check validity
openssl_certificate:
path: "{{ item.path }}"
provider: assertonly
valid_at: 20171221162800Z
register: result
loop: "{{ find_result.files }}"

ansible get rpm version of variable

I'm getting as an external-var the name of a service. I want to find the rpm version of that service.
I used the following playbook :
tasks:
- name: get the rpm or apt package facts
package_facts:
manager: "auto"
- name: get version of current installed rpm
set_fact:
rpm_version: "{{ packages['{{ service_name }}'] }}"
- name: print version of current installed rpm
debug:
msg: "{{ rpm_version }}"
I got the following error :
TASK [get version of current installed rpm] ************************************************************************************************************************************************
fatal: [10.20.10.74]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute '{{ service_name }}'\n\nThe error appears to be in '/home/m/my-playbook.yml': line 11, column 6, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: get version of current installed rpm\n ^ here\n"}
I tried using escape characters like \' but it didn't really help.
How can I pass a variable to the packages dict?
When I replace the {{ service_name }} with a hard coded name it works as expected
Try this syntax:
- name: get version of current installed rpm
set_fact:
rpm_version: "{{ ansible_facts.packages[service_name] }}"

Ansible collection not detected when running playbook on AWX

I use modules from the collection netapp.ontap in my ansible playbook which works perfectly fine when run using ansible-playbook command.
However, when run from AWX, it fails to detect the collection and immediately throws an errors that it cannot detect the ansible module/collection.
I even tried to re-install the collection from the playbook itself but with no luck.
The ansible collection is confirmed to be installed as it already works fine when run outside AWX.
The host is running ansible 2.10.4.
Here is my playbook:
---
- hosts: all
gather_facts: yes
collections:
- netapp.ontap
tasks:
- name: Install Netapp Collection from Ansible Galaxy
shell: ansible-galaxy collection install netapp.ontap
- name: Run Task
import_tasks: tasks/hil.yml
Task:
- name: 'Gather SVMs'
netapp.ontap.na_ontap_info:
state: info
hostname: "{{ netapp_hostname }}"
username: "{{ netapp_username }}"
password: "{{ netapp_hv_password }}"
gather_subset:
- vserver_info
Error from AWX:
SSH password:
Vault password:
ERROR! couldn't resolve module/action 'netapp.ontap.na_ontap_info'. This often indicates a misspelling, missing collection, or incorrect module path.
The error appears to be in '/tmp/awx_421_gey54bdw/project/tasks/hil.yml': line 6, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: 'Gather SVMs'
^ here
This one looks easy to fix. It seems that there is a value started
with a quote, and the YAML parser is expecting to see the line ended
with the same kind of quote. For instance:
when: "ok" in result.stdout
Could be written as:
when: '"ok" in result.stdout'
Or equivalently:
when: "'ok' in result.stdout"
Update:
I created a collections/requirements.yml file, with the below details but now AWX fails the task itself.
collections/requirements.yml
collections:
name: https://github.com/ansible-collections/netapp.git
type: git
Error:
"/var/lib/awx/venv/awx/lib/python3.6/site-packages/awx/main/tasks.py",
line 1279, in run self.pre_run_hook(self.instance, private_data_dir) File
"/var/lib/awx/venv/awx/lib/python3.6/site-packages/awx/main/tasks.py",
line 1862, in pre_run_hook sync_task.run(local_project_sync.id) File
"/var/lib/awx/venv/awx/lib/python3.6/site-packages/awx/main/tasks.py",
line 698, in _wrapped return f(self, *args, **kwargs) File
"/var/lib/awx/venv/awx/lib/python3.6/site-packages/awx/main/tasks.py",
line 1444, in run raise AwxTaskError.TaskError(self.instance, rc)
Exception: project_update 435 (failed) encountered an error (rc=2), please
see task stdout for details.

Ansible nxos_interface module:

I am a network engineer and new to Ansible automation, I am trying configure the Nexus switch interfaces as mentioned in the play book, I don't face issue getting result from ios_command module but issues is happening from ios_config module, I don't understand what is the issue, please help me,
I have pasted the playbook and error logs below:
---
---
- name: configure ethernet interface
hosts: nx-os
tasks:
- name: filter hostname
ios_command:
commands: "show run | inc hostname"
register: output
- name: configure interfaces
nxos_interface:
- name: "{{ item.name }}"
admin_state: up
duplex: full
speed: auto
with_items:
- name: Ethernet1/41
- name: Ethernet1/42
when: "'nx-os' in output.stdout[0]"
Error:
[DEPRECATION WARNING]: The TRANSFORM_INVALID_GROUP_CHARS settings is set to allow bad characters in group names by default, this will change, but
still be user configurable on deprecation. This feature will be removed in version 2.10. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
ERROR! unexpected parameter type in action: <class 'ansible.parsing.yaml.objects.AnsibleSequence'>
The error appears to be in '/root/ansible/bkrishna/configure_interface.yml': line 12, column 7, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: Admin down an interface
^ here
The error message is pretty explicit:
ERROR! unexpected parameter type in action: <class 'ansible.parsing.yaml.objects.AnsibleSequence'>
there are no ansible modules that accept a list as their main configuration shape, although some do accept lists for individual keys
You will want this instead:
- name: configure interfaces
nxos_interface:
name: "{{ item.name }}"
admin_state: up
speed: auto
with_items:
- # as you had before ...

How to caching Windows fact of ansible_fact to Redis?

I have ansible_fact caching using redis.
It is well gathering to cache of redis for RHEL/AIX/HPUX and using ansible_fact of playbook.
but, Windows fact is not caching to redis.
What problem? or What configuration will do?
My ansible version is
[user]$ ansible --version
ansible 2.8.0
config file = /home/user/.ansible.cfg
configured module search path = [u'/home/user/utility/module']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /bin/ansible
python version = 2.7.5 (default, Mar 26 2019, 22:13:06) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
My ansible.cfg is
$ ansible-config dump --only-changed
ANSIBLE_PIPELINING(/home/user/.ansible.cfg) = True
CACHE_PLUGIN(/home/user/.ansible.cfg) = redis
CACHE_PLUGIN_CONNECTION(/home/user/.ansible.cfg) = localhost:6379:0
CACHE_PLUGIN_TIMEOUT(/home/user/.ansible.cfg) = 86100
DEFAULT_FACT_PATH(/home/user/.ansible.cfg) = /home/user/facts.d
DEFAULT_GATHERING(/home/user/.ansible.cfg) = smart
DEFAULT_REMOTE_USER(/home/user/.ansible.cfg) = user
First playbook is well done (gather_fact: yes), gathering ansible_memtotal_mb for windows
- name: gather fact
hosts: windows
gather_facts: yes
tasks:
- name: insertline
lineinfile
path: "fact.html"
insertbefore: "</th></tr>"
line: "{{ ansible_memtotal_mb }}"
Second playbook is problem (gather_fact: no), it is not use fact for cache data and fatal error occur.
- name: gather fact
hosts: windows
gather_facts: no
tasks:
- name: insertline
lineinfile
path: "fact.html"
insertbefore: "</th></tr>"
line: "{{ ansible_memtotal_mb }}"
The ansible_memtotal_mb is not using cache data of redis, despite of using cache for redis.
TASK [(lineinfile) Save result DATA to HTML file. ****************************
Tuesday 30 July 2019 10:41:40 +0900 (0:00:00.613) 0:00:07.639 **********
fatal: [hostname]: FAILED! => {"msg": "The task includes an option with an
undefined variable. The error was: 'ansible_memtotal_mb' is undefined
The error appears to be in '/home/user/systeminfo.yml': line 73, column 7, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: (lineinfile) Save result DATA to HTML file. [\"{{ WEB_DIR }}\"]
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- \"{{ foo }}\"
"}

Resources