ansible. Run handler on specific host - ansible

I need to collect some information during run of ansible and print this information in the end.
I've tried to define empty list variable in role. I added in playbook handler which add new value to list ant print value of this variable in the end of playbook.
set_fact:
manual_tasks: "{{ manual_tasks + ['restart apache'] }}"
I miss that set_fact host related. So this solution stop working as soon as I start using different hosts. Delegate_to is not solve problem as well. Is there way to make this list global? Or any other solution exist?

Q: Add new value to list and print it at the end of the playbook. Is there way to make this list global?
A: No. It is not. "Global scope is set by config, environment variables and the command line." A host can't set_fact in the play or global scope.
You might want to take a look at ansible-runner. See Sending Runner Status and Events to External Systems.

Related

Ansible regex_replace replace multiple characters in URI

Long story short -
Task 1:
Through URI module I am querying Website to obtain json data. Output is saved to variable.
Task 2:
Json_search is used to filter data.
But result value comes with square brackets which I need to get rid off as it needs to be inserted into url address.
I am using not elegant replace module twice to solve this problem. This works but I more than sure you can engage regex_replace (or json_query in more intelligent way) to achieve same result.
Expected output: https://site1/api/host/1
Received output before using replace 2x:
https://site1/api/host/[1]
Snippet from playbook:
…
- name: display url
debug:
msg: {{ json_output_var.json|json_search('result[].id')|replace('[','')|replace(']','')

Changing list value in Ansible

I have inventory with a very complicated structure. For my specific installation I want to override only some values. For example, I have structure:
---
System:
atr1: 47
config:
- nodes:
- logger:
id: 'all'
svr: 'IEW'
- Database:
constr: 'login/pass#db'
atr2: 'some value'
I want to override severity of the logger, i.e. add statistic information
svr: 'IEWS'. I want to provide an override within --extra-vars parameter.
In ansible.cfg -> hash_behaviour = merge
I don't want to use something like - svr: "{{ svr_custom | default('IEW') }}", because there are too many parameters, and thus it will be difficult to write the entire inventory in such way.
I read about combine filter, but I can't use it, when I had to override only one item in hash.
How can I achieve my goal?
The way you found is the simplest one. It's verbose to write but very easy to debug and to fix.
If you REALLY want to shrink this job, you can write your own lookup plugin. (https://docs.ansible.com/ansible/2.5/plugins/lookup.html).
From my experience, I really want to say that direct and dumb approach (write verbose) is much better for overall maintainability. A next person will see a dumb dump (pun intended) which is easy to fix, not a some obscure python snippet.
To make life easier you may want to store this configuration as a separate file (with all jinja pieces) and use lookup (st right from docs):
# Since 2.4, you can pass in variables during evaluation
- debug: msg="{{ lookup('template', './some_template.j2', template_vars=dict(x=42)) }} is evaluated with x=42"
Moreover, you can use Jinja's |from_yaml (or from_json) to convert loaded and processed template into data structure.
I read about combine filter, but I can't use it, when I had to override only one item in hash.
Why is that? Wouldn't new_svr defined in --extra-vars achieve what you want?
- set_fact:
System: "{{ System | combine({'config':[{'nodes':[{'logger':{'svr':new_svr }}]}]}, recursive=True) }}"

How to access value from YAML key/value pair list item?

If I have the following YAML list item (I think that's what it's called) which is expressed as a key/value pair, how do I read the value? I've been looking through the YAML documentation and didn't see this situation discussed.
---
apache_vhosts:
- servername: localhost
documentroot: "/var/www/html"
I want to do something like this and set install_path to "/var/www/html":
...
# This doesn't work
install_path: "{{ apache_vhosts.servername[documentroot] }}"
apache_vhosts is a list of mappings. You are trying to access the key servername from this list, but lists don't have keys.
Also I don't know what you want to achieve with .servername[documentroot].
My guess is you need:
apache_vhosts[0].documentroot (the first element of apache_vhosts -> key documentroot)
Please have a look at the Jinja2 Template Docs.
Edit: Probably better for your case: Ansible Templating

(Ansible) How to get all inventory variables for a group of hosts as a list in template/Jinja2?

I am writing automation with this type of Ansible inventory:
[nodes]
<publicIp1> privateIp=<privateIp1>
<publicIp2> privateIp=<privateIp2>
I do this because sometimes hosts have a different public IP vs. private IP (e.g., AWS).
Now while configuring any host, I need get a csv like "privateIp1,privateIp2" inside template module's jinja2 file.
Preferrably, I do not even want to refer to the group name "node", but rather just ask for "give me list of all 'privateIp' inventory variables for all members of group of current host." << Assuming my host was a member of just one group.
If not possible, is there a way to refer to the group name and do this?
Use group magic variable. There is an exact example for your use case in the documentation, just replace the variable name:
groups is a list of all the groups (and hosts) in the inventory. This can be used to enumerate all hosts within a group. [ ]
A frequently used idiom is walking a group to find all IP addresses in that group
{% for host in groups['app_servers'] %}
{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
You can combine the template with another magic variable group_names to get a list of groups for the current host and use it as an outer loop.

Where can I find the list of supported attributes for ansible registered variables?

On Ansible you can use register: some_var in order to save information about executed task but it seems that somehow I am not able to find the list of attributes documented anywhere.
I know about some of them, but I do want a full list as I is really annoying not to have documentation.
changed – set to boolean true if something happened (useful to tell when a task has done something on a remote machine).
stderr – contains stringy output from stderr
stdout – contains stringy output from stdout
stdout_lines – contains a list of lines (i.e. stdout split on \n).
Example, how do I know if the previous task failed?
There is no comprehensive list as each module returns its own list of variables.
There are common return values, which describe what a module (should) return as a minimum.
Some modules such as shell, are kind enough to list out the return values they provide in the docs.
I agree it would be quite nice to have a comprehensive cheatsheet listing the modules and return values. As it is, we're stuck with trolling through the python code for each module.
As an example, in the case of shell (which uses command under the covers), the return values are:
module.exit_json(
cmd = args,
stdout = out.rstrip("\r\n"),
stderr = err.rstrip("\r\n"),
rc = rc,
start = str(startd),
end = str(endd),
delta = str(delta),
changed = True,
warnings = warnings
)
I can't find an official list of the attribute of a register variable either. But I noticed a fact.
Refer to the explanation of register variable in chapter Loop. Do you notice what I noticed?
Do you see the "results" part in the Json output in this page? Each key that is present in the "results" part should be the whole attributes of a register variable.
And actually you can show the list of attributes of a register variable by yourself.
See the registered variable section in chapter Variable. There is a statement saying: Use of -v when executing playbooks will show possible values for the results.
Refer below url for register module:
http://docs.ansible.com/ansible/playbooks_variables.html#registered-variables
Also if a any task fails, it will fail the whole ansible playbook and exit. to ignore that and continue we need to use below step under that task
ignore_errors: True
To debug the playbook we are executing, we should pass "-v" to debug.

Resources