Re: [ansible-project] Allow and skip empty loop

2024-04-03 Thread Vladimir Botka
On Wed, 3 Apr 2024 12:11:34 +0300
Adrian Sevcenco  wrote:

> delete_groups:
> 
> loop: "{{ delete_groups }}"
> 
> The error that i receive is:
> Invalid data passed to 'loop', it requires a list, got this instead: None.

Use the filter *default*

  loop: "{{ delete_groups | default([], true) }}"

See:
https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.default

Optionally, use the module *ansible.utils.validate*
See:
https://docs.ansible.com/ansible/latest/collections/ansible/utils/validate_module.html


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20240403140804.117e8718%40planb.


pgpf3SIGgcqB_.pgp
Description: OpenPGP digital signature


Re: [ansible-project] running handlers

2024-03-23 Thread Vladimir Botka
On Sat, 23 Mar 2024 11:12:20 -0400
Michael DiDomenico  wrote:

> ... i was hoping there was a more elegant way which
> didn't need a series of finds

The complexity is a consequence of you requirement to
"rehash the directory if the counts aren't equal". You
can't compare *counts* without at least two *finds*. The
elegant way is a single *find* and iteration of all
certificates

- find:
paths: /tmp/ansible/certs
patterns: '*.crt'
  register: out_crt

- file:
state: link
src: /tmp/ansible/certs/{{ item }}.crt
dest: /tmp/ansible/certs/{{ item }}.0
  loop: "{{ out_crt.files |
json_query('[].path') |
map('basename') |
map('splitext') |
map('first') }}"

This is, however, less efficient. The options are limited
because *file* doesn't work with wildcards. If you don't
care about idempotency and the changed/failed status
*shell* also does the job

- shell: |
cd /tmp/ansible/certs &&
for i in *.crt; do ln -s $i ${i%.crt}.0; done
  failed_when: false
  changed_when: false

You can write advanced scripts or custom filters that would
do what you want.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20240323215054.47a4d106%40planb.


pgpWlNVNvqSc8.pgp
Description: OpenPGP digital signature


Re: [ansible-project] running handlers

2024-03-22 Thread Vladimir Botka
On Fri, 22 Mar 2024 14:15:03 -0400
Michael DiDomenico  wrote:

> ... copy a bunch of ssl ca certs into a directory ...
> create *.0 symlinks to each of the certs

FWIW, instead of handlers, get the lists of the certs and
links, and iterate the difference


- find:
paths: /tmp/ansible/certs
patterns: '*.crt'
  register: out_crt

- find:
paths: /tmp/ansible/certs
patterns: '*.0'
file_type: link
  register: out_lnk

- file:
state: link
src: /tmp/ansible/certs/{{ item }}.crt
dest: /tmp/ansible/certs/{{ item }}.0
  loop: "{{ certs | difference(links) }}"
  vars:
certs: "{{ out_crt.files |
   json_query('[].path') |
   map('basename') |
   map('splitext') |
   map('first') }}"
links: "{{ out_lnk.files |
   json_query('[].path') |
   map('basename') |
   map('splitext') |
   map('first') }}"

Fit the paths to your needs.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20240322210112.70847341%40planb.


pgpd7f2n8VtxB.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Re: Incomprehensible error message

2024-01-17 Thread Vladimir Botka
On Thu, 18 Jan 2024 12:38:09 +0700
Ian Hobson  wrote:

> The comma separated list of privileges, cannot have spaces after the 
> commas.
> 
> This is unusually user-hostile!

This was fixed two years ago
https://github.com/ansible-collections/community.mysql/blob/main/plugins/module_utils/user.py#L522

See also:
https://github.com/ansible-collections/community.mysql/pull/189
https://github.com/ansible-collections/community.mysql/pull/243

--
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20240118083057.28a18ab8%40gmail.com.


pgpsWpx_fOKvT.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Another report creation problem

2024-01-15 Thread Vladimir Botka
Create the variable(s) *output*

- set_fact:
output: "{{ packages.results
|json_query('[].[name, version, release]')
|map('join','-') }}"

Then, use it(them) in the *content*

- copy:
dest: /tmp/installed.txt
content: |
  {% for host in ansible_play_hosts %}
  {{ host }}:
  The following packages will be updated
  {{ hostvars[host]['output']|to_nice_yaml }}
  {% endfor %}
  run_once: true
  delegate_to: localhost

--
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20240115160246.6e75ab7e%40gmail.com.


pgpgcxf_bpF7F.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Trying to replace single quote with regex_replace

2024-01-12 Thread Vladimir Botka
> > On Jan 10, 2024, at 12:16 PM, Vladimir Botka  wrote:
> > FWIW, convert the string to a list
> >
> > s: "['/First Datacenter/vm/Prod-SRM']"
> > l: "{{ s|from_yaml }}"

On Fri, 12 Jan 2024 09:05:16 -0800 (PST)
Dimitri Yioulos  wrote:
> how is that actually written in the playbook?


For example,

shell> cat pb1.yml
- hosts: all
  vars:
s: "['/First Datacenter/vm/Prod-SRM']"
l: "{{ s|from_yaml }}"
  tasks:
- debug:
var: l|type_debug
- debug:
var: l.0

gives (abridged)

  l|type_debug: list
  l.0: /First Datacenter/vm/Prod-SRM

But, the code in your first email shows you get *vm_facts* as
registered output of *community.vmware.vmware_guest_find*. Take a
look at the Return Values of this module
https://docs.ansible.com/ansible/latest/collections/community/vmware/vmware_guest_find_module.html#return-values

The documentation says *folders* is "list/elements=string". In this
case, no conversion is needed to get the element of the list. For
example,

shell> cat pb2.yml
- hosts: all
  vars:
vm_facts:
  folders: ['/First Datacenter/vm/Prod-SRM']
  tasks:
- debug:
var: vm_facts.folders|type_debug
- debug:
var: vm_facts.folders.0

gives (abridged)

  vm_facts.folders|type_debug: list
  vm_facts.folders.0: /First Datacenter/vm/Prod-SRM

FWIW, try community.general.yaml callback. YAML is much easier to
read compared to JSON. See
https://docs.ansible.com/ansible/latest/collections/community/general/yaml_callback.html

--
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20240112212031.226fcc47%40gmail.com.


pgp6fmFkZQx4i.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Trying to replace single quote with regex_replace

2024-01-10 Thread Vladimir Botka
> "['/First Datacenter/vm/Prod-SRM']"
> The problem is [' and ']. They can't be part pf the folder name.

FWIW, convert the string to a list

s: "['/First Datacenter/vm/Prod-SRM']"
l: "{{ s|from_yaml }}"

gives

l.0: /First Datacenter/vm/Prod-SRM

--
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20240110181644.79b47b90%40gmail.com.


pgp3_W1RyRRlt.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Ansible ping report

2023-11-08 Thread Vladimir Botka
On Wed, 8 Nov 2023 06:22:49 -0800 (PST)
Dimitri Yioulos  wrote:

> ... my goal is to see if hosts are Ansible-pingable (not
> ICMP-pingable; I believe there's a difference) or not, then take
> *all* of the output, and create a report from it. Thus, i end up
> with a report of hosts that are either Ansible-pingable or not.

Dimitri, the play does what you want. The code is available also here
https://gist.github.com/vbotka/10c57962976dd1e2dd3e9411d3745c75

Let me help you to understand it step by step

>>> - hosts: test_01,test_05,test_06,test_07 
>>>   gather_facts: false 

There are 4 hosts in the play. Setup is off, hence no connections to
the remote host up till now

>>> vars: 
>>>
>>>   h_unr: "{{ dict(ansible_play_hosts_all| 
>>>   zip(ansible_play_hosts_all| 
>>>   map('extract', hostvars, 'unr'))) }}" 

This dictionary will be evaluated when referenced in the debug task

>>> tasks: 
>>>
>>>   - block: 
>>>   - ping: 
>>> register: out 
>>>   - set_fact: 
>>>   unr: "{{ out.unreachable|d(false) }}" 
>>> ignore_unreachable: true 

Here come the first connections to the remote hosts. There are 2
tasks in the block. The first one is the Ansible module ping, not the
ICMP ping. (Yes, you're right. There is a difference.) The second one
is the module set_fact. Because of the ignore statement the tasks in
the block won't fail if a host is unreachable.

If a host can be reached by ping there is no attribute *unreachable*
in the registered dictionary *out*. Therefor, the value of the
variables *unr* will be the default (alias d) value *false*.

If a host can't be reached the value of the attribute *unreachable*
is *true*.

>>>   - debug: 
>>>   var: h_unr 
>>> run_once: true 
>>> delegate_to: localhost 

Here is the report. Let's analyse the dictionary *h_unr*. In the
above block, all hosts created the variable *unr*. When you take the
list of all hosts in the play *ansible_play_hosts_all* [1] and *map*
the function to *extract* the *hostvars* [2] variable *unr*
  
  ansible_play_hosts_all|map('extract', hostvars, 'unr')

you get a list, for example, where only the first host was reached

  [false, true, true, true]

Then, *zip* this list with *ansible_play_hosts_all*

  [[test_01,false], [test_02,true], [test_03,true], [test_04,true]]

and apply the function *dict* [3]. Below is the expected result.
Enjoy!

>>> gives (abridged) 
>>>
>>> ok: [test_01 -> localhost] => 
>>> h_unr: 
>>>   test_01: false 
>>>   test_05: true 
>>>   test_06: true 
>>>   test_07: true 

[1]
https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html
[2]
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_filters.html#selecting-values-from-arrays-or-hashtables
[3]
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_filters.html#combining-items-from-multiple-lists-zip-and-zip-longest

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231108220631.48c0146c%40gmail.com.


pgprBG_jdOr9m.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Ansible ping report

2023-11-07 Thread Vladimir Botka
Sure, here is the gist
https://gist.github.com/vbotka/10c57962976dd1e2dd3e9411d3745c75

(Is it possible to reasonably format a code in Google Groups?)
On Tuesday, November 7, 2023 at 6:55:50 PM UTC+1 dbs34 wrote:

> would you mind sharing the whole, newly updated playbook?  thank you!
>
> On Monday, November 6, 2023 at 2:58:31 PM UTC-5 Vladimir Botka wrote:
>
>> On Fri, 3 Nov 2023 08:40:19 -0700 (PDT) 
>> Dimitri Yioulos  wrote: 
>>
>> > --- PING REPORT --- 
>> > {% for pr in ping_result.results %} 
>> > {{ pr.stdout_lines | first }} 
>> > {{ pr.stdout_lines | last }} 
>> > 
>> > {% endfor %} 
>> > run_once: true 
>> > delegate_to: localhost 
>> > 
>> > That works fine. However, I want to use ansible.builtin.ping ... 
>>
>>
>> Ignore unreachable hosts in a block 
>>
>> - block: 
>> - ping: 
>> register: out 
>> - set_fact: 
>> unr: "{{ out.unreachable|d(false) }}" 
>> ignore_unreachable: true 
>>
>> and declare the dictionary 
>>
>> h_unr: "{{ dict(ansible_play_hosts_all| 
>> zip(ansible_play_hosts_all| 
>> map('extract', hostvars, 'unr'))) }}" 
>>
>> For example, the below play 
>>
>> - hosts: test_01,test_05,test_06,test_07 
>> gather_facts: false 
>>
>> vars: 
>>
>> h_unr: "{{ dict(ansible_play_hosts_all| 
>> zip(ansible_play_hosts_all| 
>> map('extract', hostvars, 'unr'))) }}" 
>>
>> tasks: 
>>
>> - block: 
>> - ping: 
>> register: out 
>> - set_fact: 
>> unr: "{{ out.unreachable|d(false) }}" 
>> ignore_unreachable: true 
>>
>> - debug: 
>> var: h_unr 
>> run_once: true 
>> delegate_to: localhost 
>>
>> gives (abridged) 
>>
>> ok: [test_01 -> localhost] => 
>> h_unr: 
>> test_01: false 
>> test_05: true 
>> test_06: true 
>> test_07: true 
>>
>> -- 
>> Vladimir Botka 
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/af3ef710-2205-48b8-9004-84da0cf9f27an%40googlegroups.com.


Re: [ansible-project] Ansible ping report

2023-11-06 Thread Vladimir Botka
On Fri, 3 Nov 2023 08:40:19 -0700 (PDT)
Dimitri Yioulos  wrote:

> --- PING REPORT ---
> {% for pr in ping_result.results %}
> {{ pr.stdout_lines | first }}
> {{ pr.stdout_lines | last }}
> 
> {% endfor %}
> run_once: true
> delegate_to: localhost
> 
> That works fine. However, I want to use ansible.builtin.ping ...


Ignore unreachable hosts in a block

- block:
- ping:
  register: out
- set_fact:
unr: "{{ out.unreachable|d(false) }}"
  ignore_unreachable: true

and declare the dictionary

  h_unr: "{{ dict(ansible_play_hosts_all|
  zip(ansible_play_hosts_all|
  map('extract', hostvars, 'unr'))) }}"

For example, the below play

- hosts: test_01,test_05,test_06,test_07
  gather_facts: false

  vars:

h_unr: "{{ dict(ansible_play_hosts_all|
zip(ansible_play_hosts_all|
map('extract', hostvars, 'unr'))) }}"

  tasks:

- block:
- ping:
  register: out
- set_fact:
unr: "{{ out.unreachable|d(false) }}"
  ignore_unreachable: true

- debug:
var: h_unr
  run_once: true
  delegate_to: localhost

gives (abridged)

ok: [test_01 -> localhost] => 
  h_unr:
    test_01: false
test_05: true
test_06: true
test_07: true

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231106205809.164c42fb%40gmail.com.


pgpEoJmLL1d_d.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Re: how to set different backup directory than current while using backup=yes

2023-10-31 Thread Vladimir Botka
On Tue, 31 Oct 2023 05:17:35 -0700 (PDT)
Todd Lewis  wrote:

> There is no backup system. ... I wouldn't have been able 
> to create such a thing ... I wouldn't dare use it in 
> production ... the rest of us have to build our 
> wheels with the stick-n-stones within our reach.
> 
> On Monday, October 30, 2023 at 11:34:33 AM UTC-4 Brian Coca wrote:
> 
> > The backup system returns the 'backup_file' information so you can
> > then operate on the built in backup, like moving it to a central
> > location ...

This can be achieved with ~20 lines of code. For example, let's
declare the module defaults

- hosts: all
  module_defaults:
lineinfile:
  create: true
  backup: true

and register the results

  tasks:

- lineinfile:
path: /tmp/test1.txt
line: "{{ item }}"
  loop: [line1, line2, line3]
  register: ns_result_001

- lineinfile:
path: /tmp/test2.txt
line: line1
  register: ns_result_0021

- lineinfile:
path: /tmp/test2.txt
line: line2
  register: ns_result_0022

Declare the list of all variables *ns_result_* and declare the list
of all backup files

  vars:

my_ns_results: "{{ q('vars', *q('varnames', '^ns_result_*')) }}"

ns_bfiles: "{{ (my_ns_results|json_query('[].backup') +
my_ns_results|json_query('[].results[].backup'))|
flatten|select }}"

Fetch the backup files to the controller and optionally delete them on
the remote hosts

  post_tasks:

- fetch:
src: "{{ item }}"
dest: /tmp/ansible/backup
  loop: "{{ ns_bfiles }}"

- file:
src: "{{ item }}"
state: absent
  loop: "{{ ns_bfiles }}"
  when: ns_bfiles_delete|d(false)|bool

For example,

shell> tree /tmp/ansible/backup/
/tmp/ansible/backup/
└── test_11
└── tmp
├── test1.txt.7143.2023-10-31@14:18:07~
    ├── test1.txt.7156.2023-10-31@14:18:08~
└── test2.txt.7182.2023-10-31@14:18:11~

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231031152959.3f0004d7%40gmail.com.


pgp6GljosgDtl.pgp
Description: OpenPGP digital signature


Re: [ansible-project] ansible looking for templates in previous role

2023-10-30 Thread Vladimir Botka
> On Friday, October 27, 2023 at 11:15:45 AM UTC-4 Brian Coca wrote:
> 
> > You can just post a simple reproducer, from what you posted I can only
> > vaguely guess that you are using the 2nd role tasks as tasks and not
> > as a role.

On Mon, 30 Oct 2023 07:48:05 -0700 (PDT)
Kathy L  wrote:

> What I did today was to remove mitogen and run it with "normal" ssh and it 
> did not have that problem.  That makes it a mitogen problem I think. I'll 
> find a bug report with them.

Post a simple reproducer here before you file the issue. Included or
depending role might be causing the problem. This might be an issue
with Ansible. See https://stackoverflow.com/a/76994183/6482561


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231030161716.4a3184ba%40gmail.com.


pgphhiTHN07sx.pgp
Description: OpenPGP digital signature


Re: [ansible-project] template for rows in a table

2023-10-20 Thread Vladimir Botka
On Fri, 20 Oct 2023 08:40:56 -0700 (PDT)
Veera  wrote:

> the "cols" are printed as like below (not as [green, red, yellow, 
> blue]).
> ...
> "msg": [
> [
> "green",
> "toronto",
> "English"
> ],
> [
> "red",
> "montreal",
> "French"
> ],
> [
> "yellow",
> "mumbai",
> "Hindi"
> ],
> [
> "blue",
> "dubai",
> "Arabic"
> ]
> ]

> > On Fri, 20 Oct 2023, 16:08 Vladimir Botka  wrote:
> >  
> >>   msg: |-
> >> colorcities lang
> >> greentorontoEnglish
> >> red  montreal   French
> >> yellow   mumbai Hindi
> >> blue dubai  Arabic

What you see depends on the callback. Try

  shell> ANSIBLE_STDOUT_CALLBACK=yaml ansible-playbook playbook.yml

Learn about formatting:

* Try filters: *to_yaml*, *to_nice_yaml*. Try the option *indent*
* Try the filter *indent*
* Try other callbacks

Links:

https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_filters.html#formatting-data-yaml-and-json
https://jinja.palletsprojects.com/en/latest/templates/#jinja-filters.indent
https://docs.ansible.com/ansible/latest/plugins/callback.html
https://docs.ansible.com/ansible/latest/collections/index_callback.html
https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-stdout-callback


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231020195605.25f8d502%40gmail.com.


pgpT7h2SWla05.pgp
Description: OpenPGP digital signature


Re: [ansible-project] template for rows in a table

2023-10-20 Thread Vladimir Botka
Declare the list of columns

  fnames: [color, cities, lang]

and get the columns

  cols: |
{% filter from_yaml %}
{% for i in fnames %}
- {{ lookup('vars', i ) }}
{% endfor %}
{% endfilter %}

gives

  cols:
- [green, red, yellow, blue]
- [toronto, montreal, mumbai, dubai]
- [English, French, Hindi, Arabic]

Find the maximal lengths

  max: "{{ cols|map('map', 'length')|map('max') }}"

gives

  max: [6, 8, 7]

and create the list of formats

  frmt: |
{% filter from_yaml %}
{% for i in max %}
- '%-{{ i }}s   '
{% endfor %}
{% endfilter %}

gives

  frmt: ['%-6s   ', '%-8s   ', '%-7s   ']

Get the rows

- set_fact:
rows: "{{ rows|d(cols.0)|zip(item)|map('flatten') }}"
  loop: "{{ cols[1:] }}"

gives

  rows:
- [green, toronto, English]
- [red, montreal, French]
- [yellow, mumbai, Hindi]
- [blue, dubai, Arabic]

 and write the table

- debug:
msg: |
  {% for i in range(fnames|length) %}
  {{ frmt[i] % fnames[i] }}{% endfor %}

  {% for j in rows %}
  {% for i in range(fnames|length) %}
  {{ frmt[i] % j[i] }}{% endfor %}

  {% endfor %}

gives

  msg: |-
colorcities lang
greentorontoEnglish
red  montreal   French
yellow   mumbai Hindi
blue dubai  Arabic

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231020160828.02da4038%40gmail.com.


pgpDcDNYf39mz.pgp
Description: OpenPGP digital signature


Re: [ansible-project] split for data manitpulation

2023-10-14 Thread Vladimir Botka
On Sat, 14 Oct 2023 10:32:51 -0700 (PDT)
Veera  wrote:

> Is there a way to combine the 2 positional  values ...
> to print  like below
>   - two
>   - four five

Split the string and trim the items

  arr: "{{ myline|split(',')|map('trim') }}"

gives

  arr:
  - This line is a test
  - two
  - three
  - four
  - five
  - '6'
  - seven

A list of lists the structure that describes what you want

  s1_34: "{{ [[1], [3, 4]]|
   map('map', 'extract', arr)|
   map('join', ' ') }}"

gives

  s1_34:
  - two
  - four five

You can substitute *arr* in *s1_34* if you want a 'one-liner'.


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231014213815.4d34a4de%40gmail.com.


pgpayI00Z88D5.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Formatting the dict items with debug

2023-10-14 Thread Vladimir Botka
On Sat, 14 Oct 2023 01:01:28 -0700 (PDT)
Veera  wrote:

> - debug:
> msg: "{{ result.stdout }}"
> 
> ok: [localhost] => {
> "msg": {
> "access_token": "xx",
> "expires_in": 43200,
> "token_type": "xx"
> }
> }

For example, given the file

shell> cat /tmp/test.json 
{
"access_token": "xx",
"expires_in": 43200,
"token_type": "xx"
}

The value of *result.stdout* is *AnsibleUnsafeText*. What you see
depends on the callback. The below play

shell> cat pb.yml
- hosts: all
  tasks:
- command: cat /tmp/test.json
  register: result
- debug:
var: result.stdout

gives JSON with the default callback

shell> ANSIBLE_STDOUT_CALLBACK=default ansible-playbook pb.yml
  ...
ok: [localhost] => {
"result.stdout": {
"access_token": "xx",
"expires_in": 43200,
"token_type": "xx"
}
}

The same task gives YAML with the yaml callback

shell> ANSIBLE_STDOUT_CALLBACK=yaml ansible-playbook pb2.yml
  ...
ok: [localhost] => 
  result.stdout:
access_token: xx
expires_in: 43200
token_type: xx

You can test the type of the attribute *stdout*

- debug:
var: result.stdout|type_debug

gives

  result.stdout|type_debug: AnsibleUnsafeText


>  filter the access token alone

Convert the text to dictionary and get the *access_token* as well.
It's up to you where you put the vars

  vars:

test_data: "{{ result.stdout|from_json }}"
access_token: "{{ test_data.access_token }}"

Example of a complete playbook for testing

shell> cat pb.yml
- hosts: all

  vars:

test_data: "{{ result.stdout|from_json }}"
access_token: "{{ test_data.access_token }}"

  tasks:

- command: cat /tmp/test.json
  register: result
- debug:
var: result.stdout
- debug:
var: result.stdout|type_debug
- debug:
var: test_data|type_debug
- debug:
var: test_data
- debug:
var: access_token


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231014172804.3f085226%40gmail.com.


pgpJQrJn3h_61.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Not Able To Flatten nested List

2023-10-10 Thread Vladimir Botka
> my_dict:
> {
> 100098f2b3a1f324 : myserver3_host4
> 100098f2b3a12635 : myserver3_host5
> 100098f2b3a14633 : myserver11_host3
> 100098f2b3a1d541 : myserver11_host1
> }


storage_details_combined:
  - server_name: myserver3.domain.org
wwns_dict:
  host4: '0x100098f2b3a1f324'
  host5: '0x100098f2b3a12635'
wwns_pmax_list:
- 100098f2b3a12635
- 100098f2b3a1f324
  - server_name: myserver11.domain.org
wwns_dict:
  host1: '0x100098f2b3a1d541'
  host3: '0x100098f2b3a14633'
wwns_pmax_list:
- 100098f2b3a1d541
- 100098f2b3a14633

Use Jinja

my_dict: |
  {% filter from_yaml %}
  {% for i in storage_details_combined %}
  {% set srv=i.server_name|split('.')|first %}
  {% for k,v in i.wwns_dict.items() %}
  {{ v[2:] }}: {{ srv }}_{{ k }}
  {% endfor %}
  {% endfor %}
  {% endfilter %}


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231010144145.2f755472%40gmail.com.


pgpCcvZ9OUVU3.pgp
Description: OpenPGP digital signature


Re: [ansible-project] override variable from outside role

2023-10-09 Thread Vladimir Botka
On Mon, 9 Oct 2023 09:18:36 +1300
Kosala Atapattu  wrote:

> Have you considered the following?
> 
> - hosts: all
>   roles:
> - name: nftables
>   forward_policy: drop
> - name: router
>   forward_policy: allow

This is not a solution to the problem:

  You have two roles and want to override defaults in the first role
  by the variables from the second role.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231009140006.4a6b7bc6%40gmail.com.


pgpVZlr4M9t0X.pgp
Description: OpenPGP digital signature


Re: [ansible-project] override variable from outside role

2023-10-08 Thread Vladimir Botka
On Sun, 8 Oct 2023 23:36:47 +1300
Kosala Atapattu  wrote:

> I did not fully understand the problem, but might worth having a look at
> variable precedence

The problem is as follows: You have two roles and want to override
defaults in the first role by the variables from the second role.

The precedence of variables is a substantial part of the solution. It
is not sufficient though. There might be more solutions depending on
the use-case's details. An option might be creating the below task in
the second role

  shell> cat roles/role2/tasks/instantiate_vars.yml   
  - set_fact:
  var1_common: "{{ var1_common }}"
when: var1_common is defined

and "instantiate" the variable(s) before you run the first role. This
way *set_fact* (precedence 19.) overrides the roles' defaults
(precedence 2.)

  shell> cat pb.yml
  - hosts: all
pre_tasks:
  - include_role:
  name: role2
  tasks_from: instantiate_vars
run_once: true
roles:
  - role1

Notes:

* You don't have to include or import *instantiate_vars.yml* in role2.
* You can "instantiate* more variables.
* You have to keep in mind the limitation of this solution. Only
  precedence 20.-22. are left to override such "instantiated"
  variables.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231008132003.318a2584%40gmail.com.


pgpNMHHwfCvBX.pgp
Description: OpenPGP digital signature


Re: [ansible-project] override variable from outside role

2023-10-06 Thread Vladimir Botka
There are many other options on how to override defaults.
The solution might be simple if you provide the detail. See
https://en.wikipedia.org/wiki/Minimal_reproducible_example

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231006210315.1e1ead55%40gmail.com.


pgpXnA_XNKlPf.pgp
Description: OpenPGP digital signature


Re: [ansible-project] override variable from outside role

2023-10-05 Thread Vladimir Botka
On Wed, 4 Oct 2023 20:45:23 -0500
"'Matt Zagrabelny' via Ansible Project"
 wrote:

> > PLAY [all] *
> >
> > TASK [nftables : debug] 
> > ok: [zed] =>
> >   forward_policy: drop

> I would like forward_policy to be "accept" for the nftables role ...
> I want the "router" role to affect ... "nftables" role.

Create task that will "instantiate" the variable *forward_policy*

shell> cat roles/router/tasks/instantiate_vars.yml 
- set_fact:
forward_policy: "{{ forward_policy }}"
  when: forward_policy is defined

and run it in the first play *pre_tasks*

shell> cat pb.yml
- hosts: all
  pre_tasks:
- include_role:
name: router
tasks_from: instantiate_vars
  run_once: true
  roles:
- nftables

- hosts: router
  roles:
- router


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231005081108.4be4f4cc%40gmail.com.


pgpX9M9yblTJM.pgp
Description: OpenPGP digital signature


Re: [ansible-project] override variable from outside role

2023-10-04 Thread Vladimir Botka
> $ cat roles/nftables/defaults/main.yaml
> forward_policy: drop
> 
> $ cat roles/router/vars/main.yaml
> forward_policy: accept
> 
> I don't know how to override the variable in the nftables role from within
> the router role.

Is it possible to minimize the example?

shell> tree .
.
├── hosts
├── pb.yml
└── roles
├── nftables
│   ├── defaults
│   │   └── main.yml
│   └── tasks
│   └── main.yml
└── router
├── tasks
│   └── main.yml
└── vars
└── main.yml

shell> cat roles/nftables/defaults/main.yml 
forward_policy: drop
shell> cat roles/nftables/tasks/main.yml 
- debug:
var: forward_policy

shell> cat roles/router/vars/main.yml 
forward_policy: accept
shell> cat roles/router/tasks/main.yml 
- debug:
var: forward_policy

shell> cat hosts
[router]
zed
shell> cat pb.yml 
- hosts: all
  roles:
- nftables

- hosts: router
  roles:
- router

Running the playbook gives

shell> ansible-playbook pb.yml

PLAY [all] *

TASK [nftables : debug] 
ok: [zed] =>
  forward_policy: drop

PLAY [router] **

TASK [router : debug] **
ok: [zed] =>
  forward_policy: accept

Does this reproduce your problem? If yes what do you expect?


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20231005003836.3b6eaaed%40gmail.com.


pgp7O6lhChJRn.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Retrieving items from a dictionary

2023-09-27 Thread Vladimir Botka
Map the attribute

  dn: "{{ ansible_mounts|
  selectattr('device', 'contains', 'nas-server.example.com')|
  map(attribute='device') }}"

If you want to skip empty lists test the length

  - debug:
  var: dn
when: dn|length > 0

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230927213245.3f39b2f8%40gmail.com.


pgpHL7pnDuN1i.pgp
Description: OpenPGP digital signature


Re: [ansible-project] How to remove a single item from a list within a nested dictionary

2023-08-25 Thread Vladimir Botka
On Fri, 25 Aug 2023 06:19:39 -0700 (PDT)
jean-christophe manciot  wrote:

> We need to remove the item ''44  from the list  located 
> inside the dictionary matched by the key/value  net_id=='1'.

Put the items you want to update into a dictionary. For example,

diff:
  '1': [44]

Use Jinja to update the list

update: |
  {% filter from_yaml %}
  {% for i in vpc.provider %}
  {% if i.net_id in diff %}
  {% set nic_ids=i.nic_ids|difference(diff[i.net_id]) %}
  - {{ i|combine({'nic_ids': nic_ids}) }}
  {% else %}
  - {{ i }}
  {% endif %}
  {% endfor %}
  {% endfilter %}

Then, create the dictionary

new_vpc:
  provider: "{{ update }}"



-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230825185728.09b6f5f9%40gmail.com.


pgpZHIwAG1rUk.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Simpler way to define many handlers?

2023-08-24 Thread Vladimir Botka
On Thu, 24 Aug 2023 17:46:58 +0200
Dick Visser  wrote:

> Is there perhaps another way to avoid having a ton of very similar)
> handlers?

It is not, IMHO, if you want to do it in a single run of a playbook.

It is possible to create handlers from meta-data and template(s) and
then import them. Similar to the concept of the *configure* script
https://en.wikipedia.org/wiki/Configure_script

I'm not saying Ansible should generally adopt this concept. I think,
in some cases such configuration might make the project robuster,
simpler, and easily extendable. FWIW, it's feasible to control some
projects by structured meta-data only
https://ansible-config-light.readthedocs.io/en/latest/qsg.html


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230825001028.66b4cefc%40gmail.com.


pgpqGc32vuRsb.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Loopless alternative?

2023-08-17 Thread Vladimir Botka
On Thu, 17 Aug 2023 13:11:25 -0400
Brian Coca  wrote:

> see map/select/reject filters .. they are actually loops and normally
> much simpler than using jinja command syntax ( {% %} ).

Unfortunately, some filters are not *map* friendly. For example, the
filter *product*

  list1|product(list2) .. works fine
  list1|zip(list2)|map('product') ... does not work


Details: Given the list

  l1:
- dir: /tmp/test/d1
  sub_dir: [a, b]
- dir: /tmp/test/d2
  sub_dir: [a, b, c]

the goal is to create the list of products

  l2:
  - /tmp/test/d1/a
  - /tmp/test/d1/b
  - /tmp/test/d2/a
  - /tmp/test/d2/b
  - /tmp/test/d2/c

The iteration (the filter *subelements* not used
to demonstrate the functionality of *product*)

- debug:
msg: "{{ [item.0]|product(item.1) }}"
  loop: "{{ dirs|zip(sdirs) }}"
  vars:
dirs: "{{ l1|map(attribute='dir') }}"
sdirs: "{{ l1|map(attribute='sub_dir') }}"

works as expected. Gives (abridged)

  msg:
  - - /tmp/test/d1
- a
  - - /tmp/test/d1
- b

  msg:
  - - /tmp/test/d2
- a
  - - /tmp/test/d2
- b
  - - /tmp/test/d2
- c

But, the filter *product* doesn't work with *map*

  dirs: "{{ l1|map(attribute='dir') }}"
  sdirs: "{{ l1|map(attribute='sub_dir') }}"
  l3: "{{ dirs|zip(sdirs)|map('product') }}"

gives

  l3:
  - - - /tmp/test/d1
- - - a
- b
  - - - /tmp/test/d2
- - - a
- b
- c

This leaves you with Jinja if you want to avoid the loops in tasks

  l3: |
{% filter from_yaml %}
{% for i in l1 %}
{% for s in i.sub_dir %}
- {{ i.dir }}/{{ s }}
{% endfor %}
{% endfor %}
{% endfilter %}

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230817202944.3f3512c8%40gmail.com.


pgpzQmp4GVXoP.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Loopless alternative?

2023-08-17 Thread Vladimir Botka
On Thu, 17 Aug 2023 07:56:58 -0400
Todd Lewis  wrote:

>bn:
>- - basename
>  - dev_wss_db
>- - basename
>  - dev_wss_db_requests
>- - basename
>  - dev_bss_service_database
>- - basename
>  - dev_bss_frontend_db
>- - basename
>  - dev_mss_db
> 
> But I didn't find a way to map that using "community.general.dict" to create
> 
>bn:
>- basename: dev_wss_db
>- basename: dev_wss_db_requests
>- basename: dev_bss_service_database
>- basename: dev_bss_frontend_db
>- basename: dev_mss_db

You can always use brute-force Jinja as the last resort. For example,
given the list

  bn_list:
  - dev_wss_db
  - dev_wss_db_requests
  - dev_bss_service_database
  - dev_bss_frontend_db
  - dev_mss_db

the below Jinja creates the list of the hashes

  bn: |
{% filter from_yaml %}
{% for basename in bn_list %}
- basename: {{ basename }}
{% endfor %}
{% endfilter %}

As a side-note, this is equivalent to

  bn: "{{ all_objects|
  map(attribute='Key')|
  map('regex_replace', bn_regex, '{basename: \\1}')|
  map('from_yaml') }}"
 
> This for me is one of the more frustrating things about Jinja
> pipelines. I keep wishing "map" would take arbitrary
> expressions rather than the limited set it's stuck with.

This is very good point. It would be possible to write such a filter.
However, I'm not sure about the security implications.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230817170740.038163cc%40gmail.com.


pgpOgqpg7TAic.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Loopless alternative?

2023-08-16 Thread Vladimir Botka
On Thu, 17 Aug 2023 00:46:08 +0200
Vladimir Botka  wrote:

> Create the list of the hashes
> 
>   bn_regex: '^{{ prefix }}\d{10}_(.*)\.pgdump$'
>   bn: "{{ all_objects|
>   map(attribute='Key')|
>   map('regex_replace', bn_regex, '\\1')|
>   map('community.general.dict_kv', 'basename') }}"
> 
> gives
> 
>   bn:
>   - basename: dev_wss_db
>   - basename: dev_wss_db_requests
>   - basename: dev_bss_service_database
>   - basename: dev_bss_frontend_db
>   - basename: dev_mss_db

There are options. Filter *basename* and get rid of *prefix*

  bn_regex: '^\d{10}_(.*)\.pgdump$'
  bn: "{{ all_objects|
  map(attribute='Key')|
  map('basename')|
  map('regex_replace', bn_regex, '\\1')|
  map('community.general.dict_kv', 'basename') }}"

Create the hash in *regex_replace* and use *from_yaml* instead
of *community.general.dict_kv*

  bn: "{{ all_objects|
  map(attribute='Key')|
  map('basename')|
  map('regex_replace', bn_regex, '{basename: \\1}')|
  map('from_yaml') }}"

Instead of *regex_replace* use *splitext* and *split*

  bn: "{{ all_objects|
  map(attribute='Key')|
  map('basename')|
  map('splitext')|map('first')|
  map('split', '_', 1)|map('last')|
  map('community.general.dict_kv', 'basename') }}"


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230817013426.387bc3d6%40gmail.com.


pgpIJbMNdKKpL.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Loopless alternative?

2023-08-16 Thread Vladimir Botka
Create the list of the hashes

  bn_regex: '^{{ prefix }}\d{10}_(.*)\.pgdump$'
  bn: "{{ all_objects|
  map(attribute='Key')|
  map('regex_replace', bn_regex, '\\1')|
  map('community.general.dict_kv', 'basename') }}"

gives

  bn:
  - basename: dev_wss_db
  - basename: dev_wss_db_requests
  - basename: dev_bss_service_database
  - basename: dev_bss_frontend_db
  - basename: dev_mss_db

zip the lists and combine the items

  backup_object: "{{ all_objects|zip(bn)|map('combine') }}"


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230817004608.1a07c1ff%40gmail.com.


pgpFTDB_f6ZbO.pgp
Description: OpenPGP digital signature


Re: [ansible-project] deferred evaluation (?)

2023-07-27 Thread Vladimir Botka
Create a template. For example,

shell> cat create_test.j2
{% for i in strings %}
{{ i }} = {{ '{{' }} {{ i }} {{ '}}' }}
{% endfor %}

Then, the below playbook

shell> cat pb.yml
- hosts: localhost
  tasks:
- template:
src: create_test.j2
dest: /tmp/test.j2
  vars:
strings:
  - '0'
  - '1'
  - "['aa', 'bb', 'cc']|intersect(['bb', 'cc'])"
  - "['aa', 'bb', 'cc']|intersect(['bb', 'cc'])|length > 0"
- debug:
msg: "{{ lookup('template', '/tmp/test.j2') }}"

gives abridged

  msg: |-
0 = 0
1 = 1
['aa', 'bb', 'cc']|intersect(['bb', 'cc']) = ['bb', 'cc']
['aa', 'bb', 'cc']|intersect(['bb', 'cc'])|length > 0 = True

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230728052731.289a5791%40gmail.com.


pgpgWSQj23O6C.pgp
Description: OpenPGP digital signature


Re: [ansible-project] deferred evaluation (?)

2023-07-27 Thread Vladimir Botka
post expected result

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230728000322.23e6f83b%40gmail.com.


pgpsIXqSvv9xn.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Issue when iterating over hostvars attribute

2023-07-11 Thread Vladimir Botka
On Tue, 11 Jul 2023 20:42:30 +0100
Jorge Rúa  wrote:

>   loop:
> - "{{ hostvars[inventory_hostname]['hostgroups'] }}"
> 
> TASK [ Adding servers to each respective hostgroup]
> *
> ok: [aaa -> localhost] => (item=['foobar_service_web',
> 'foobar_service_unstable']) => {

Try

  - debug:
  msg: "echo {{ inventory_hostname }} {{ item }}"
    loop: "{{ hostgroups|from_yaml }}"

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230711221153.04e65fc5%40gmail.com.


pgpN61HNffQvq.pgp
Description: OpenPGP digital signature


Re: [ansible-project] 'until' loop label invisible, and not possible to customise?

2023-07-07 Thread Vladimir Botka
On Fri, 7 Jul 2023 12:30:08 -0400
Brian Coca  wrote:

> > (The condition is evaluated on the remote host).

> No, conditions (as well as any templating) is always evaluated on the
> controller, the caveat is that DATA for this evaluation might come
> from the remote host. via `register:`.

Right. The *task_executor* takes care of this
https://github.com/ansible/ansible/blob/devel/lib/ansible/executor/task_executor.py#L775

I was too quick. The registered variable can be used in the label. If
the status of the task (changed) is available when the label is
displayed the registered variable should be available as well. For
example,


- command: "echo {{ item }}"
  register: status
  loop: [1, 2, 3, 4, 5]
  loop_control:
label: "{{ status.stdout|int + 10 }}"
  until: status.stdout|int < 4
  delay: 1

gives

TASK [command]
***
changed: [test_11] => (item=11)
changed: [test_11] => (item=12)
changed: [test_11] => (item=13)
FAILED - RETRYING: [test_11]: command (3 retries left).
FAILED - RETRYING: [test_11]: command (2 retries left).
FAILED - RETRYING: [test_11]: command (1 retries left).
failed: [test_11] (item=14) => changed=true 
  ansible_loop_var: item
  attempts: 3
  cmd:
  - echo
  - '4'
  delta: '0:00:00.015013'
  end: '2023-07-07 21:06:24.412645'
  item: 4
  msg: ''
  rc: 0
  start: '2023-07-07 21:06:24.397632'
  stderr: ''
  stderr_lines: 
  stdout: '4'
  stdout_lines: 
FAILED - RETRYING: [test_11]: command (3 retries left).
FAILED - RETRYING: [test_11]: command (2 retries left).
FAILED - RETRYING: [test_11]: command (1 retries left).
failed: [test_11] (item=15) => changed=true 
  ansible_loop_var: item
  attempts: 3
  cmd:
  - echo
  - '5'
  delta: '0:00:00.015014'
  end: '2023-07-07 21:06:33.054414'
  item: 5
  msg: ''
  rc: 0
  start: '2023-07-07 21:06:33.039400'
  stderr: ''
  stderr_lines: 
  stdout: '5'
  stdout_lines: 


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230707232117.3bd70888%40gmail.com.


pgp1F55tATWUl.pgp
Description: OpenPGP digital signature


Re: [ansible-project] 'until' loop label invisible, and not possible to customise?

2023-07-07 Thread Vladimir Botka
On Fri, 7 Jul 2023 11:54:02 +0200
Dick Visser  wrote:

>   loop_control:
> label: status.stdout
> extended: true
> 
> does not work...
> 
> Is there a way to do this?

It is not, I'm afraid. The controller will see the value of *status*
after the loop completes. (The condition is evaluated on the remote
host).

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230707124859.34958414%40gmail.com.


pgprp4LaGXMSb.pgp
Description: OpenPGP digital signature


Re: [ansible-project] splitting the output of {{ ansible_play_name }}

2023-07-06 Thread Vladimir Botka
On Thu, 6 Jul 2023 09:10:48 +0200 (CEST)
dulhaver via Ansible Project  wrote:

> ansible_play_name is i.e. POSTGRES_get_utf8.
> How can I only get POSTGRES

Try this

  {{ ansible_play_name|split('_')|first }}

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230706094301.00c46681%40gmail.com.


pgp4nlx0m_SHv.pgp
Description: OpenPGP digital signature


Re: [ansible-project] loading tasks file based on ansible_fqdn value

2023-07-03 Thread Vladimir Botka
On Sun, 2 Jul 2023 17:12:33 +0200 (CEST)
dulhaver via Ansible Project  wrote:

> - ansible.builtin.set_fact:
> level: keycloak
>   when: ansible_fqdn == VM-0312.step.zrz.internal

Make your live easier and put the logic into the *vars*. For example,

  shell> cat group_vars/all/level.yml
  level_dict:
VM-0311.step.zrz.internal: passkey
VM-0312.step.zrz.internal: keycloak
VM-0313.step.zrz.internal: falsekey
  level: "{{ level_dict[ansible_fqdn] }}"

Given the inventory for testing

  shell> cat hosts
  host1 ansible_fqdn=VM-0311.step.zrz.internal
  host2 ansible_fqdn=VM-0312.step.zrz.internal
  host3 ansible_fqdn=VM-0313.step.zrz.internal

use *set_fact" if you want to 'instantiate' the variable (put the
variable into the *hostvars*). You can omit *set_fact* if you don't
need hostvars.*.level. For example, the play

  - hosts: all
tasks:
  - set_fact:
  level: "{{ level }}"
  - debug:
  var: level

gives (abridged)

  ok: [host1] => 
level: passkey
  ok: [host2] => 
level: keycloak
  ok: [shot3] => 
level: falsekey

As a result, the code is cleaner. Also the concentration of data into
a single point of failure (a dictionary and assignment isolated in
*vars*) makes the code more robust.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230703113413.5372d6c1%40gmail.com.


pgp4HQt7dfawf.pgp
Description: OpenPGP digital signature


[ansible-project] Re: Ansible task execution until it completes

2023-06-22 Thread Vladimir Botka
On Thu, 22 Jun 2023 10:55:32 +
Aharonu  wrote:

> ...
> Can we get output of only MSG instead of listing all other output so that i
> can see the required output?

This is the list of the records *variable_data.msg.records*

I can't provide you with better answer without "Minimal reproducible
example". https://en.wikipedia.org/wiki/Minimal_reproducible_example

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230622180408.3b57e762%40gmail.com.


pgpWAqYB4j7QP.pgp
Description: OpenPGP digital signature


Re: [ansible-project] How to dynamically end a loop in Ansible

2023-06-21 Thread Vladimir Botka
See "Ansible loop interface redesign #140"
https://github.com/ansible/proposals/issues/140

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230622011939.35e3f9e1%40gmail.com.


pgpDUF0z1wXpS.pgp
Description: OpenPGP digital signature


Re: [ansible-project] How to dynamically end a loop in Ansible

2023-06-21 Thread Vladimir Botka
On Wed, 21 Jun 2023 18:56:23 -0400
ibelieve06  wrote:

> ... I need to dynamically end the loop earlier (lets say 5 iterations
> instead of 10 as defined by the loop: statements).

You can't end it. You can only skip the rest. For example,

- command: "echo {{ item }}"
  with_sequence: end=5
  register: out
  when: out.stdout|d(0)|int < 3

gives (on localhost)

  changed: [localhost] => (item=1)
  changed: [localhost] => (item=2)
  changed: [localhost] => (item=3)
  skipping: [localhost] => (item=4) 
  skipping: [localhost] => (item=5)

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230622010745.43089da2%40gmail.com.


pgpg5AdA3wTuJ.pgp
Description: OpenPGP digital signature


[ansible-project] Re: Ansible task execution until it completes

2023-06-21 Thread Vladimir Botka
On Wed, 21 Jun 2023 19:34:21 +
Aharonu  wrote:

>   - name: run ontap rest cli command to check volume move status
> netapp.ontap.na_ontap_rest_cli:
>   <<: *login
>   hostname: "{{ inventory_hostname }}"
>   command: 'volume/move?fields=percent-complete,state'
>   params:
> volume: '*'
> vserver: '*'
>   verb: 'GET'
> register: variable_data
> ...
>
> TASK [debug] 
> ok: [cluster1] => {
> "variable_data": {
> "changed": true,
> "failed": false,
> "msg": {
> "num_records": 3,
> "records": [
> {
> "percent_complete": 30,
> "state": "done",
> "volume": "vol1",
> "vserver": "svm1"
> },
> {
> "percent_complete": 98,
> "state": "healthy",
> "volume": "vol2",
> "vserver": "svm1"
> },
> {
> "percent_complete": 50,
> "state": "done",
> "volume": "vol1",
> "vserver": "svm2"
> }
> ]
> }
> }
> }

Try the tasks below. Register the *variable_data* in the first task
and use it in the starting *until* condition of the second task. You
want to repeat it every 1 minute. Set *delay* 60 seconds and *retry*
for example 60 times (1 hour)

  - netapp.ontap.na_ontap_rest_cli:
  <<: *login
  hostname: "{{ inventory_hostname }}"
  command: 'volume/move?fields=percent-complete,state'
  params:
volume: '*'
vserver: '*'
  verb: 'GET'
register: variable_data

  - netapp.ontap.na_ontap_rest_cli:
  <<: *login
  hostname: "{{ inventory_hostname }}"
  command: 'volume/move?fields=percent-complete,state'
  params:
volume: '*'
vserver: '*'
  verb: 'GET'
register: variable_data
until: variable_data.msg.records|
   selectattr('percent_complete', 'ne', 100)|
   list|length == 0
delay: 60
retry: 60

This way you are actually monitoring the volumes. But, Ansible can't
provide you with any intermediate data. The task is running on the
remote host and you'll see the results once the task completes and
returns the results to the controller.

Try to configure NetApp system monitors if you want to see any
progress . See
https://docs.netapp.com/us-en/cloudinsights/task_system_monitors.html#monitor-descriptions


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230622003939.574e99a0%40gmail.com.


pgpj4bs4mzFPZ.pgp
Description: OpenPGP digital signature


[ansible-project] Re: Ansible task execution until it completes

2023-06-21 Thread Vladimir Botka
On Wed, 21 Jun 2023 11:08:16 +
Aharonu  wrote:

> The conditional check 'data_done' failed. The error was: Unexpected
> templating type error occurred on ({{ variable_data|
> selectattr('percent_complete', 'ne', 100) | length == 0 }}): object of type
> 'generator' has no len()

Add the explicit conversion to *list*

  data_done: "{{ variable_data|
 selectattr('percent_complete', 'ne', 100)|
 list|length == 0 }}"

This has already been fixed. If you can update the latest version.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230621182935.45d476aa%40gmail.com.


pgpJDifScjNp8.pgp
Description: OpenPGP digital signature


[ansible-project] Re: Ansible task execution until it completes

2023-06-21 Thread Vladimir Botka
On Tue, 20 Jun 2023 22:18:22 +0530
Aharonu  wrote:

> I have *variable_data *which contains 3 records. I want to keep run
> *debug *task
> continuously every 1 minute until *percent_complete* == 100 and then
> complete task execution.

Given the list for testing

  variable_data:
- {percent_complete: 100, volume: vol1, vserver: svm1}
- {percent_complete: 100, volume: vol2, vserver: svm1}
- {percent_complete: 100, volume: vol3, vserver: svm2}

a task will complete when all *percent_complete* == 100

  data_done: "{{ variable_data|
 selectattr('percent_complete', 'ne', 100)|
 length == 0 }}"

Without knowing the source of *variable_data* it's not possible to
tell you how such a task should look like. Generally, you should test
*data_done*, set delay, and how many times you want to retry

  until: data_done
  delay: 60
  retries: 999

See "Retrying a task until a condition is met*
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_loops.html#retrying-a-task-until-a-condition-is-met

Moving forward you should briefly describe at least: the inventory,
the source of the items(tasks, processes, ...) to be completed, and
how you consolidate *variable_data*.

Make it "Minimal reproducible example". See
https://en.wikipedia.org/wiki/Minimal_reproducible_example


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230621083618.30b488d1%40gmail.com.


pgp6Ulp6wz2ka.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Loop files that will be used as variables

2023-06-18 Thread Vladimir Botka
On Wed, 14 Jun 2023 04:07:38 -0700 (PDT)
"dudu.c...@gmail.com"  wrote:

> *My J2 file* 
> 
> select * from {{ item.id}} where {{ item.color}} 
> 
> *My input files*
> 
> *File-1.yml :*
> Id: 1
> color: blue 
> 
>  *File-2**.yml** :*
> Id: 2
> color: red 
> 
> *My Playbook – that is not working. *
> - hosts: localhost
>   become: true
>   gather_facts: yes
>   tasks:
> - name: 
>   template:
> src: /opt/input.sql.j2
> dest: /opt//{{item.id}}.sql
>   with_items:
> - file-1.yaml
> 
> - file-2.yaml
> 
> *The output files I wish to have *
> 
> 1.sql 
> select * from 1 where blue 
> 
> 2.sql 
> select * from 2 where red

Given the files

  shell> cat file-1.yaml 
  id: 1
  color: blue

  shell> cat file-2.yaml 
  id: 2
  color: red

Read the files in the loop. Test it

  shell> cat pb.yml 
  - hosts: localhost
tasks:
  - debug:
  var: i
loop:
  - file-1.yaml
  - file-2.yaml
vars:
  i: "{{ lookup('file', item )|from_yaml }}"

gives (abridged)

  TASK [debug]
  
  ok: [localhost] => (item=file-1.yaml) => ansible_loop_var: item
i:
  color: blue
  id: 1
item: file-1.yaml
  ok: [localhost] => (item=file-2.yaml) => 
ansible_loop_var: item
i:
  color: red
  id: 2
item: file-2.yaml

The variable *item* keeps the name of the current file in the loop.
You have to use the variable *i* both in the template file

  shell> cat input.sql.j2
  select * from {{ i.id }} where {{ i.color }}

and in the *template* task. The play

  shell> cat pb.yml 
  - hosts: localhost
tasks:
  - template:
  src: input.sql.j2
  dest: "/tmp/{{ i.id }}.sql"
loop:
  - file-1.yaml
  - file-2.yaml
vars:
  i: "{{ lookup('file', item )|from_yaml }}"

creates the files

  shell> cat /tmp/1.sql 
  select * from 1 where blue

  shell> cat /tmp/2.sql 
  select * from 2 where red


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230618085129.7afc8696%40gmail.com.


pgpSCcKQC7ffv.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Loop Not Able to Parse After First iteration

2023-06-12 Thread Vladimir Botka
On Mon, 12 Jun 2023 11:52:43 -0700 (PDT)
javed khan Siddque  wrote:

>   vars:
> isilon_cluster_name_p: "server"
> primary_data_center: "SSDC"
> region: "SC"
> division: "HOS"
> app_id: "1234"
> env: "D"
> my_app_id: "{{ '{:>05}'.format(app_id) }}"
> my_seq_id: "{{ '%02d' | format(item) }}"
> list_of_sequence: "{{ range(1, 10) | list }}"
> ...
> "msg": [
> [
> "/ifs/SSDC/server/HOSSCD0123401",
> "/ifs/SSDC/server/HOSSCD0123402",
> "/ifs/SSDC/server/HOSSCD0123403",
> "/ifs/SSDC/server/HOSSCD0123404",
> "/ifs/SSDC/server/HOSSCD0123405",
> "/ifs/SSDC/server/HOSSCD0123406",
> "/ifs/SSDC/server/HOSSCD0123407",
> "/ifs/SSDC/server/HOSSCD0123408",
> "/ifs/SSDC/server/HOSSCD0123409"
> ]
> ]

Given the variables for testing

  center: "SSDC"
  cluster: "server"
  division: "div"
  region: "reg"
  env: "env"
  app_id: "1234"
  list_of_sequence: "{{ range(1, 10) }}"

Declare *path*, *prefix*, and *app*. You have to convert *app_id*
from string to integer because you quotes the number

  path: "/ifs/{{ center }}/{{ cluster }}"
  prefix: "{{ division }}{{ region }}{{ env }}"
  app: "{{ '%05d' % (app_id|int) }}"

Use Jinja template to create the list

  my_list: |
{% filter from_yaml %}
{% for i in list_of_sequence %}
- {{ path }}/{{ prefix|upper }}{{ app }}{{ '%02d' % (i) }}
{% endfor %}
{% endfilter %}

gives

  my_list:
  - /ifs/SSDC/server/DIVREGENV0123401
  - /ifs/SSDC/server/DIVREGENV0123402
  - /ifs/SSDC/server/DIVREGENV0123403
  - /ifs/SSDC/server/DIVREGENV0123404
  - /ifs/SSDC/server/DIVREGENV0123405
  - /ifs/SSDC/server/DIVREGENV0123406
  - /ifs/SSDC/server/DIVREGENV0123407
  - /ifs/SSDC/server/DIVREGENV0123408
  - /ifs/SSDC/server/DIVREGENV0123409


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230613001138.21d21387%40gmail.com.


pgpsHUtq_FCUS.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Question about source files in an Ansible Collection

2023-06-08 Thread Vladimir Botka
On Thu, 8 Jun 2023 04:42:48 -0700 (PDT)
"lift...@gmail.com"  wrote:

> ...
> - name: Copy the RPM locally
>   ansible.builtin.copy:
> src: files/mysql-connector-j-8.0.33-1.el7.noarch.rpm
> dest: /var/tmp/
> owner: root
> group: root
> mode: 0644
> remote_src: true

This copy is rather confusing. You said the directory *files* is in a
role, i.e. on the controller. Now you set *remote_src: true* which
takes the source from the remote host.

To isolate the problem. You should verify each step you make. In this
case, before you run *yum*, verify the file
*/var/tmp/mysql-connector-j-8.0.33-1.el7.noarch.rpm* is present and
readable.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230608145250.63fea001%40gmail.com.


pgpKINmHPNEdC.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Question about source files in an Ansible Collection

2023-06-07 Thread Vladimir Botka
On Wed, 7 Jun 2023 11:16:35 -0700 (PDT)
"lift...@gmail.com"  wrote:

> - ansible.builtin.yum:
> name: files/mysql-connector-j-8.0.33-1.el7.noarch.rpm
> 
> I even tried to copy the file locally using the copy module with the 
> remote_src flag set to true, but I get the same "file not found" error.  

Absolute path on the remote host is required

  if spec.endswith('.rpm') or '://' in spec:
  if '://' not in spec and not os.path.exists(spec):
  res['msg'] += "No RPM file matching '%s' found on system" % spec

https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/yum.py#L1040


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230608021025.7d1fb785%40gmail.com.


pgpMLO71NKjcL.pgp
Description: OpenPGP digital signature


Re: [ansible-project] check connectivity (telnet

2023-06-05 Thread Vladimir Botka
On Mon, 5 Jun 2023 11:53:44 +0200 (CEST)
dulhaver via Ansible Project  wrote:

> probably I did not make myself clear enough

No. Your statement can't be clearer: "to check whether postgres1 has
a connection via port 5432 to a specific IP address"
https://groups.google.com/g/ansible-project/c/dkR80nKr25Q/m/rVRrMlTbBAAJ

> >   - hosts: postgres1
> > tasks:
> >   - wait_for:
> >   host: 
> >   port: 5432  
> 
> I guess this would check whether 'postgres1' can connect to
> :5432. What I wanted to check ... whether
> *postgres1* would be ready to accept connections from  address>:5432


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230605130752.2165b095%40gmail.com.


pgpYT9yQ2ElM3.pgp
Description: OpenPGP digital signature


Re: [ansible-project] check connectivity (telnet

2023-06-04 Thread Vladimir Botka
On Sun, 4 Jun 2023 12:06:39 +0200 (CEST)
dulhaver via Ansible Project  wrote:

> ... couple of postgres-remotes ...
> ... to check whether postgres1 has a connection via port 5432 to a specific 
> IP address ...
> ... what would be the right approach (aka module) for such in an Ansible TASK?

Use the module *wait_for*. See
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/wait_for_module.html


If you run the play on *postgres1* the task is simple

  - hosts: postgres1
tasks:
  - wait_for:
  host: 
  port: 5432

If you run the play on multiple hosts you might want to run
once and delegate the task 

  - hosts: all
tasks:
  - wait_for:
  host: 
  port: 5432
delegate_to: postgres1
run_once: true

See: pg_isready
https://www.postgresql.org/docs/current/app-pg-isready.html

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230604133822.77edfdfe%40gmail.com.


pgpb_WiJgBzw3.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Gather Facts failed due resolve hostname inventory_hostname

2023-06-01 Thread Vladimir Botka
Try to isolate your problem:

* Create the inventory

shell> cat hosts
[test]
NEXUS3172P

[test:vars]
ansible_host=10.131.88.10
ansible_network_os=nxos
username=
password=x

* Create a simple playbook

shell> cat pb.yml
- hosts: NEXUS3172P
  gather_facts: false
  tasks:
- nxos_facts:
gather_subset: hardware

* Debug the connection (-)

shell> ansible-playbook -i hosts - pb.yml


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230602010112.5e8a9bf3%40gmail.com.


pgp5mEigoMWbc.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Gather Facts failed due resolve hostname inventory_hostname

2023-06-01 Thread Vladimir Botka
*ansible_host* and *ansible_ssh_host* are the same when you use
*ansible.builtin.ssh* connection plugin. See
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/ssh_connection.html#parameter-host

In your case, *ansible_network_os=nxos* indicates that you use
*ansible.netcommon.network_cli* connection plugin. This plugin
doesn't recognise *ansible.builtin.ssh*. See
https://docs.ansible.com/ansible/latest/collections/ansible/netcommon/network_cli_connection.html#parameter-host

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230602003900.4a3a12f2%40gmail.com.


pgpXT9Upoovy4.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Gather Facts failed due resolve hostname inventory_hostname

2023-06-01 Thread Vladimir Botka
> https://docs.ansible.com/ansible/latest/collections/ansible/builtin/ssh_connection.html#parameter-remote_user

Errata

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/ssh_connection.html#parameter-host



-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230601234925.24d87b60%40gmail.com.


pgpOK8I2Vp3k5.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Gather Facts failed due resolve hostname inventory_hostname

2023-06-01 Thread Vladimir Botka
On Thu, 1 Jun 2023 16:49:39 -0400
Todd Lewis  wrote:

> In your first post you were setting ansible_ssh_host=10.131.88.10, not 
> ansible_host.

Both are ansible_host and ansible_ssh_host are valid. See
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/ssh_connection.html#parameter-remote_user


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230601234708.1e791d76%40gmail.com.


pgpfewhi2__KG.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Configuring Ansible to prioritize a specific Python interpreter or automatically discover one

2023-04-29 Thread Vladimir Botka
On Sat, 29 Apr 2023 00:56:33 -0700 (PDT)
Haji Hogson  wrote:

> automatically discover the ... appropriate Python interpreter ...
> /usr/bin/python3 if available ... and fall back to automatic
> discovery otherwise.

See the configuration parameter INTERPRETER_PYTHON_FALLBACK
https://docs.ansible.com/ansible/latest/reference_appendices/config.html#interpreter-python-fallback

You can put it into the inventory file
ansible_interpreter_python_fallback=['/usr/bin/python3','/usr/bin/python']

See also the configuration parameter INTERPRETER_PYTHON
https://docs.ansible.com/ansible/latest/reference_appendices/config.html#interpreter-python

The fallback will be used if INTERPRETER_PYTHON is not available.
"The fallback behavior will issue a warning that the interpreter
should be set explicitly..." You can chose a discovery mode (default
auto).


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230429120033.54c13e8c%40gmail.com.


pgphg99Ugi820.pgp
Description: OpenPGP digital signature


Re: [ansible-project] merging lists

2023-04-18 Thread Vladimir Botka
On Tue, 18 Apr 2023 10:40:40 -0400
Todd Lewis  wrote:

>  - debug: msg="{{ [list_12, list_34, list_56] | sum(start=[]) }}"

Isn't *flatten* simpler?

  - debug: msg="{{ [list_12, list_34, list_56] | flatten }}"


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230418191211.7dc11ce0%40gmail.com.


pgp4SlUMvyE7j.pgp
Description: OpenPGP digital signature


Re: [ansible-project] merging lists

2023-04-17 Thread Vladimir Botka
On Mon, 17 Apr 2023 19:29:02 -0400
Michael DiDomenico  wrote:

> thanks for the help, but that's not exactly what i am after.  i'm
> attempting to avoid creating a third variable.  but maybe that's the
> only way

You can avoid the third variable if you want to. For example,

  a: [1, 2, 3]
  b: "{{ a + [4, 5, 6] }}"

will add the lists

  b: [1, 2, 3, 4, 5, 6]

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230418070023.661358dd%40gmail.com.


pgpOQ29aUZfYl.pgp
Description: OpenPGP digital signature


Re: [ansible-project] merging lists

2023-04-17 Thread Vladimir Botka
On Mon, 17 Apr 2023 18:22:10 -0400
Michael DiDomenico  wrote:

> lista:
> - { one: 'str1', two: 'str2' }
> 
> listb:
> - "{{ lookup('vars','lista') }}"
> - { one: 'str1', two: 'str2' }
> 
> the output i want is
> 
> listb:
> { one: 'str1', two: 'str2' },
> { one: 'str1', two: 'str2' }
> 
> but what i get is
> 
> listb:
> [ { one: 'str1', two: 'str2' } ],
> { one: 'str1', two: 'str2' }

The lookup *vars* is not necessary. Reference the variable

  listb:
- "{{ lista }}"
- {one: str1, two: str2}

You should get

  listb:
- - one: str1
two: str2
- one: str1
  two: str2

This is correct. The first item on the list *listb* is list *lista*.
If you put two items into the list *lista*

  lista:
- one: str1
  two: str2
- ccc: str3
  ddd: str4

you'll get

  listb:
- - one: str1
two: str2
  - ccc: str3
ddd: str4
- one: str1
  two: str2

You can *flatten* the list

   listc: "{{ listb|flatten }}"

gives

  listc:
- one: str1
  two: str2
- ccc: str3
  ddd: str4
- one: str1
  two: str2

However, a simpler option is adding lists. For example, given two
lists

  lista:
- {one: str1, two: str2}
- {ccc: str3, ddd: str4}
  listb:
- {one: str1, two: str2}

Declare the list *listc*. This will merge the two lists

  listc: "{{ lista + listb }}"


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230418010528.33cdd05c%40gmail.com.


pgpQ1CSW5eqn5.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Need to automate task via bastion host

2023-04-16 Thread Vladimir Botka
Hi Monica,

On Sun, 16 Apr 2023 00:23:14 -0700 (PDT)
Monica  wrote:

> Hi  Vladimir Botka,
> Looking for your support on this.

You said you can "connect to the remote host via bastion host
using ssh".

shell> ssh user@@ -p 8022

Let me ask you first. Wouldn't an Ansible controller in the internal
network serve you use-case better?

 ext_net <-> bastion_host <-> ansible_controller <-> remote_host

You should store you projects in a version control. Why don't you
clone the projects on the controller and run your playbooks from
there? This has many advantages:

 * The configuration is simpler
 * You can limit the external SSH access to single host
 * Playbooks in the local network run faster
 * The execution of the projects don't depend on the throughput and
   quality of the external network
 * You can use *ansible-pull* on the controller to update the
   projects automatically
 * You can schedule the projects' updating to off-peak times

Why do you want to run Ansible via proxy?

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230416132743.16fb3f4a%40gmail.com.


pgpluFiJdA3XJ.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Parsing csv file and running shell command

2023-04-14 Thread Vladimir Botka
On Thu, 13 Apr 2023 21:14:42 -0700 (PDT)
"alonso...@gmail.com"  wrote:

> ---
>   - name: Read Users
> gather_facts: True
> hosts: localhost
> 
> tasks:
> - name: Read users
>   read_csv:
> path: users.csv
> delimiter: ","
>   register: s3list
> 
> - name: Running command
>   command: 
> echo "aws s3 cp {{ s3.source }}" {{ s3.destination }} -- recursive 
> --acl-parameters ---profile prod'
>   loop: "{{ s3list.list }}"
>   loop_control:
> loop_var: s3
> 
> the csv file contents:
> source,destination
> S3://mybucket/puppy/test.jpg,S3://mybucket2/trying/
> S3://mybucket/puppy/ds.jpg,S3://mybucket3/trying/
> S3://mybucket/puppy/as.jpg,S3://mybucket4/trying/
> S3://mybucket/puppy/was.jpg,S3://mybucket5/trying/
> S3://mybucket/puppy/qaes.jpg,S3://mybucket6/trying/
> 
> When I run the playbook I am getting the following
> TASK [Running command] 
> *
> changed: [localhost] => (item={'source': 'S3://mybucket/puppy/test.jpg', 
> 'destination': 'S3://mybucket2/trying/'})
> changed: [localhost] => (item={'source': 'S3://mybucket/puppy/ds.jpg', 
> 'destination': 'S3://mybucket3/trying/'})
> changed: [localhost] => (item={'source': 'S3://mybucket/puppy/as.jpg', 
> 'destination': 'S3://mybucket4/trying/'})
> changed: [localhost] => (item={'source': 'S3://mybucket/puppy/was.jpg', 
> 'destination': 'S3://mybucket5/trying/'})
> changed: [localhost] => (item={'source': 'S3://mybucket/puppy/qaes.jpg', 
> 'destination': 'S3://mybucket6/trying/'})

You're not running the *aws* command. You're testing the *aws* command
with *echo*. Actually, this is a good idea to see the commands before
you run them. Register the results and take a look at *stdout*.

In the module *command*, there is a couple of syntax problems
in the run-string. To make the syntax both simpler and easier to read
use the *folded style*. See
https://yaml.org/spec/1.2.2/#813-folded-style

The tasks below

- command: >-
echo
aws s3 cp
{{ item.source }}
{{ item.destination }}
--recursive --acl parameters --profile prod
  loop: "{{ s3list.list }}"
  register: out
- debug:
msg: "{{ out.results|map(attribute='stdout')|list }}"

should give you what you want

  msg:
  - aws s3 cp S3://mybucket/puppy/test.jpg S3://mybucket2/trying/
--recursive --acl parameters --profile prod
  - aws s3 cp S3://mybucket/puppy/ds.jpg S3://mybucket3/trying/
--recursive --acl parameters --profile prod
  - aws s3 cp S3://mybucket/puppy/as.jpg S3://mybucket4/trying/
--recursive --acl parameters --profile prod
  - aws s3 cp S3://mybucket/puppy/was.jpg S3://mybucket5/trying/
--recursive --acl parameters --profile prod
  - aws s3 cp S3://mybucket/puppy/qaes.jpg S3://mybucket6/trying/
--recursive --acl parameters --profile prod

If this is what you want remove *echo* and run the *aws* command with
the option *--dryrun*

- command: >-
aws s3 cp
{{ item.source }}
{{ item.destination }}
--dryrun --recursive --acl parameters --profile prod
  loop: "{{ s3list.list }}"
  register: out
- debug:
var: out

If everything is alright copy the files

- command: >-
aws s3 cp
{{ item.source }}
{{ item.destination }}
--recursive --acl parameters --profile prod
  loop: "{{ s3list.list }}"
  register: out
- debug:
    var: out

Notes:

* You can remove the option *--recursive* as long as you copy single
  files
* You'll have to replace *parameters* with actual values. See
  https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230414082342.214a2322%40gmail.com.


pgpTXEzalt13Q.pgp
Description: OpenPGP digital signature


Re: [ansible-project] ssh-key exchange and root password set

2023-03-29 Thread Vladimir Botka
On Wed, 29 Mar 2023 19:56:23 +0900
Prady A  wrote:

> #ansible-playbook -i inventory ssh_install.yml *-k*
> ... avoid the -k option

Use *ssh-agent*.
https://www.ssh.com/academy/ssh/agent

It is a bad practice to *ssh* to root. See
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_privilege_escalation.html

> password: "{{ 'PLAIN_PASSWORD' | password_hash('sha512') }}"

See how to use Ansible vault
https://docs.ansible.com/ansible/latest/cli/ansible-vault.html

The next option is *passwordstore*
https://www.passwordstore.org/

See the Ansible *passwordstore* lookup plugin
https://docs.ansible.com/ansible/latest/collections/community/general/passwordstore_lookup.html


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230329140245.257f0080%40gmail.com.


pgpjzvwp8hxc3.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Failed host list from 'rescue' task

2023-03-15 Thread Vladimir Botka
On Wed, 15 Mar 2023 17:44:55 +
Aharonu  wrote:

> I am working to get failed hosts from 'rescue' section into a CSV file.
> [...]
> > *when  i tried to append data to a list. *  
> 
> > - set_fact:
> > failed_list: "{{ failed_list + [ansible_host] }}"
> 
> *failed_hosts.csv:*
> *number of failed hots: 2*
> *hostname:*
> *bogus1*
> *bogus2*

Each host will have its own variable *failed_list*. Therefore, it
makes no sense to record *ansible_host* in this list. Instead, you
might want to record the failed tasks. For example, the block below
runs three tasks. If any of the tasks fails the name of it will be
added to the list *failed_list*

- name: block A
  block:
- name: task1A
  command: "{{ ['true', 'false']|random }}"
- name: task2A
  command: "{{ ['true', 'false']|random }}"
- name: task3A
  command: "{{ ['true', 'false']|random }}"
  rescue:
- set_fact:
failed_list: "{{ failed_list +
 [ansible_failed_task.name] }}"

Create dictionary of all hosts and failed tasks

  failed_lists: "{{ dict(groups.all|
zip(hostvars|dict2items|
map(attribute='value.failed_list',
default=[]))) }}"

For example, given the inventory

  shell> cat hosts
  host_A ansible_host=10.1.0.61
  host_B ansible_host=10.1.0.62
  host_C ansible_host=10.1.0.63

a play running two blocks (A and B) on two hosts (host_A and host_C)
gives

  failed_lists:
host_A: [task1A, task1B]
host_B: []
host_C: [task3A, task2B]

Declare the list of failed hosts by selecting nonempty lists

  failed_hosts: "{{ failed_lists|dict2items|
selectattr('value')|
map(attribute='key')|list }}"

gives

  failed_hosts: [host_A, host_C]

Now you can create reports. For example, to write the file on the
controller, delegate the task to localhost 

- copy:
dest: /tmp/failed_hosts.yaml
content: |
  number_of_failed_hosts: {{ failed_hosts|length }}
  hostnames: {{ failed_hosts|join(', ') }}
  {% for h,l in failed_lists.items() %}
  {{ h }}: {{ l|sort|join(', ') }}
  {% endfor %}
  delegate_to: localhost
  run_once: true

gives the YAML file

  shell> cat /tmp/failed_hosts.yaml 
  number_of_failed_hosts: 2
  hostnames: host_A, host_C
  host_A: task1A, task1B
  host_B: 
  host_C: task2B, task3A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
Example of a complete playbook for testing

---
- hosts: host_A,host_C

  vars:

failed_list: []
failed_lists: "{{ dict(groups.all|
  zip(hostvars|dict2items|
  map(attribute='value.failed_list',
  default=[]))) }}"
failed_hosts: "{{ failed_lists|dict2items|
  selectattr('value')|
  map(attribute='key')|list }}"

  tasks:

- name: block A
  block:
- name: task1A
  command: "{{ ['true', 'false']|random }}"
- name: task2A
  command: "{{ ['true', 'false']|random }}"
- name: task3A
  command: "{{ ['true', 'false']|random }}"
  rescue:
- set_fact:
failed_list: "{{ failed_list +
 [ansible_failed_task.name] }}"

- name: block B
  block:
- name: task1B
  command: "{{ ['true', 'false']|random }}"
- name: task2B
  command: "{{ ['true', 'false']|random }}"
- name: task3B
  command: "{{ ['true', 'false']|random }}"
  rescue:
- set_fact:
failed_list: "{{ failed_list +
 [ansible_failed_task.name] }}"

- block:
- debug:
var: failed_lists|to_yaml
- debug:
var: failed_hosts|to_yaml
  run_once: true

- copy:
dest: /tmp/failed_hosts.yaml
content: |
  number_of_failed_hosts: {{ failed_hosts|length }}
  hostnames: {{ failed_hosts|join(', ') }}
  {% for h,l in failed_lists.items() %}
  {{ h }}: {{ l|sort|join(', ') }}
  {% endfor %}
  delegate_to: localhost
  run_once: true

- block:
- include_vars:
file: /tmp/failed_hosts.yaml
name: test
- debug:
var: test
  run_once: true
...


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230316002416.11d4a3c7%40gmail.com.


pgpWv9i4PU0yT.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Track list of failed/success tasks into a file.

2023-03-09 Thread Vladimir Botka
See https://ansible-runner.readthedocs.io/en/stable/

The artifacts will keep data to create the report.


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230310011626.3635b9c9%40gmail.com.


pgp9JvTMdbGdQ.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Ansible variable data to CSV file

2023-03-07 Thread Vladimir Botka
On Mon, 6 Mar 2023 19:09:21 +
Aharonu  wrote:

> "csv": [
> "cluster1,virtual_clu1,log_vol1,online,used",
> "cluster1,virtual_clu1,log_vol2,offline,not_used",
> "cluster1,virtual_clu1,log_vol3_Test,online,not_used",
> "cluster1,virtual_clu1,log_vol4,offline,not_used",
> "cluster2,virtual_clu2,log_vol6,online,used",
> "cluster2,virtual_clu2,log_vol1,offline,not_used",
> "cluster2,virtual_clu2,log_vol3,online,not_used"
> "cluster2,virtual_clu2,log_vol4,online,used"
> ]
> 
> *Looking for:*
> The header must be:  cluster_name,log_cluster,vol_name,status,work_status
> 
> not working:
> (it has to give here when status=online and  work_status=not_used )
> exclude:
> (it has go give here when status=offline and  vol_name= 'Test'>)  
> working:
> (it has to give here when status=online and work_status=used
> [other then not working & exclude list] )
> 
> *example: file1.csv*
> 
> not working:
> cluster_name,log_cluster,vol_name,status,work_status
> cluster2,virtual_clu2,log_vol3,online,not_used
> 
> exclude:
> cluster_name,log_cluster,vol_name,status,work_status
> cluster1,virtual_clu1,log_vol3_Test,online,not_used
> cluster1,virtual_clu1,log_vol2,offline,not_used
> cluster1,virtual_clu1,log_vol4,offline,not_used
> cluster2,virtual_clu2,log_vol1,offline,not_used
> 
> working:
> cluster_name,log_cluster,vol_name,status,work_status
> cluster1,virtual_clu1,log_vol1,online,used
> cluster2,virtual_clu2,log_vol6,online,used
> cluster2,virtual_clu2,log_vol4,online,used

Put the header into the list

  header: [cluster_name, log_cluster, vol_name, status, work_status]

and use the filter *community.general.dict* to create the dictionary

  csv_dict: "{{ csv|
map('split', ',')|
map('zip', header)|
map('map', 'reverse')|
map('community.general.dict') }}"

gives

  csv_dict:
  - cluster_name: cluster1
log_cluster: virtual_clu1
status: online
vol_name: log_vol1
work_status: used
  - cluster_name: cluster1
...

Select the subsets

  notworking: "{{ csv_dict|
  selectattr('status', '==', 'online')|
  selectattr('work_status', '==', 'not_used') }}"
  exclude: "{{ csv_dict|
   selectattr('status', '==', 'offline')|
   selectattr('vol_name', 'regex', '^log_vol[1-4]$') }}"
  working: "{{ csv_dict|
   selectattr('status', '==', 'online')|
   difference(notworking)|
   difference(exclude) }}"

and write them to the files. Test it first

- debug:
msg: |
  dest: {{ item.1 }}
  {{ item.0 }}:
  {{ header|join(',') }}
  {% for l in lookup('vars', item.0) %}
  {{ l.values()|join(',') }}
  {% endfor %}
  loop:
- [notworking, fiel1.csv]
- [exclude, fiel2.csv]
- [working, fiel3.csv]

gives (abridged)

  msg: |-
dest: fiel1.csv
notworking:
cluster_name,log_cluster,vol_name,status,work_status
cluster1,virtual_clu1,log_vol3_Test,online,not_used
cluster2,virtual_clu2,log_vol3,online,not_used

  msg: |-
dest: fiel2.csv
exclude:
cluster_name,log_cluster,vol_name,status,work_status
cluster1,virtual_clu1,log_vol2,offline,not_used
cluster1,virtual_clu1,log_vol4,offline,not_used
cluster2,virtual_clu2,log_vol1,offline,not_used

  msg: |-
dest: fiel3.csv
working:
cluster_name,log_cluster,vol_name,status,work_status
cluster1,virtual_clu1,log_vol1,online,used
cluster2,virtual_clu2,log_vol6,online,used
cluster2,virtual_clu2,log_vol4,online,used


Notes:

* There are two items in *notworking* not only one

* The line where vol_name='log_vol3_Test' shouldn't be in the set
  *exclude* because of the condition status=='offline'. Fit the regex
  to your needs.

  cluster1,virtual_clu1,log_vol3_Test,online,not_used


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230307101422.2ce5d380%40gmail.com.


pgpuWsCqpWct5.pgp
Description: OpenPGP digital signature


Re: [ansible-project] How to use version compare test in selectattr?

2023-03-06 Thread Vladimir Botka
On Mon, 06 Mar 2023 15:56:32 +0100
"'Kai Stian Olstad' via Ansible Project"
 wrote:

>  - debug:
>  msg:
>{{ my | selectattr('vers', 'version', '"5", "<"' }}

This is the correct syntax

- debug:
msg: |
  {{ my | selectattr('vers', 'version', '5', '<') }}


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230306163951.0872d4c9%40gmail.com.


pgpKdDsihffjX.pgp
Description: OpenPGP digital signature


Re: [ansible-project] split with multiple columns in debug

2023-02-27 Thread Vladimir Botka
On Mon, 27 Feb 2023 21:07:45 -0800 (PST)
Veera  wrote:

> load_avg: "{{ up_out.stdout_lines[0].split()[7:] }}"

Given the registered variable *up_out*

  - command: uptime
register: up_out

Use the filter community.general.jc to parse the stdout. The utility
*jc* "converts the output of many commands, file-types, and strings
to JSON or YAML". For example,

  uptime: "{{ up_out.stdout|community.general.jc('uptime') }}"

gives

  uptime:
load_15m: 1.21
load_1m: 1.84
load_5m: 1.41
time: 07:57:41
time_hour: 7
time_minute: 57
time_second: 41
uptime: 11 days, 18:12
uptime_days: 11
uptime_hours: 18
uptime_minutes: 12
uptime_total_seconds: 1015920
users: 2

The first three attributes come from "load average". Quoting from man
uptime: "The averages are taken over the three time intervals." Now,
the usage is trivial. For example,

  load_average: >
{{ uptime.load_1m }},
{{ uptime.load_5m}},
{{ uptime.load_15m }}

gives

  load_average: |-
1.84, 1.41, 1.21

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230228081123.140af349%40gmail.com.


pgpPtlL5zDkW9.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Re: need help with if condition in jinja template

2023-02-26 Thread Vladimir Botka
On Sun, 26 Feb 2023 18:11:02 -0800 (PST)
Kenady Inampudi  wrote:

>  {% for host in ansible_play_hosts_all %}
>  {% if 'Completed Successfully' not in hostvars[host]['mksys']['msg'] %}
> 
> This condition generates nothing.

Your code works as expected. For testing, put the variable into the inventory

  shell> cat hosts
  all:
hosts:
  host1:
mksys:
  msg: 'Completed Successfully'
  host2:
mksys:
  msg: 'Completed Successfully'
  host3:
mksys:
  msg: 'Completed Not Successfully'

The playbook

  shell> cat pb.yml
  - hosts: all
tasks:
  - debug:
  msg: |
{% for host in ansible_play_hosts_all %}
{% if 'Completed Successfully' not in 
hostvars[host]['mksys']['msg'] %}
{{ host }} msg:{{hostvars[host]['mksys']['msg'] }}
{% endif %}
{% endfor %}
run_once: true

gives (abridged)

  msg: |-
host3 msg:Completed Not Successfully


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230227044225.1a0e72e9%40gmail.com.


pgpmAhiizcL2_.pgp
Description: OpenPGP digital signature


Re: [ansible-project] problem quoting string

2023-02-20 Thread Vladimir Botka
On Mon, 20 Feb 2023 07:03:54 -0800 (PST)
"gregory@gmail.com"  wrote:

> Hello, 
> 
> having something like this in my playbook
> vars:
>   somevar: 
>  command:
> - run: | 
> "somecommand 'somestring' | awk '{print $2}'"
> 
> tasks:
>- name: output var to file
>   copy:
>   content: "{{ somevar | to_nice_yaml(sort_keys=false,indent=2) }}"
>dest: /tmp/tempfile
>  
> when I look at /tmp/tempfile it looks like ansible doubles apostrophes:
> command:
>  -- run: '"somecommand ''somestring'' | awk ''{print $2}''"
> 
> is there any way to make ansible produce file without extra apostrophes?
> 
> thanks.
> 

Let's simplify the variable for testing

  cmd: |
"somecommand 'somestring'"


1) The filters *to_yaml* and *to_nice_yaml* will quote the strings

- copy:
dest: /tmp/tempfile
content: "{{ cmd|to_yaml }}"

gives (note the empty line and the closing single-quote

shell> cat /tmp/tempfile
'"somecommand ''somestring''"

  '

Remove the trailing new line by adding the dash to the block

  cmd: |-
"somecommand 'somestring'"

now the task creates the file

shell> cat /tmp/tempfile
'"somecommand ''somestring''"'

In a single-quoted block, the single-quote is the only character that
have to be escaped; by itself. This is the reason of the 'extra
apostrophes'.

2) Add the dash to your block to remove the new line

  somevar: 
 command:
   - run: |-
   "somecommand 'somestring' | awk '{print $2}'"

The filter *to_nice_yaml* will quote the string

- copy:
dest: /tmp/tempfile
content: "{{ somevar|to_nice_yaml }}"

gives valid YAML with the list *command* and single item

shell> cat /tmp/tempfile
command:
-   run: '"somecommand ''somestring'' | awk ''{print $2}''"'

Read the file and use the command

- include_vars:
 file: /tmp/tempfile
- command: "echo {{ command.0.run }}"
  register: out
- debug:
var: out.stdout

gives probably what you want

  out.stdout: somecommand 'somestring' | awk '{print $2}'

The run-string was properly expanded and used in the command line.

3) If you really want to get rid of the 'extra apostrophes' you'll
have to expand the strings in the template. For example,

- copy:
dest: /tmp/tempfile
content: |
  {% for key,val in somevar.items() %}
  {{ key }}:
  {% for i in val %}
  {% for k,v in i.items() %}
  - {{ k }}: {{ v }}
  {% endfor %}
  {% endfor %}
  {% endfor %}

gives

shell> cat /tmp/tempfile
command:
- run: "somecommand 'somestring' | awk '{print $2}'"

Note that now the double-quotes are not part of the string stored
in command.0.run


HTH,

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230220175659.1b0cc62f%40gmail.com.


pgpyCI1jHAmyM.pgp
Description: OpenPGP digital signature


Re: [ansible-project] How to split string twice in ansible playbook hosts section.

2022-12-27 Thread Vladimir Botka
> On Tue, Dec 27, 2022 at 7:04 AM Know-Your-Tech  wrote:
> >
> > ansible-playbook -i /web/aes/admin/playbooks/updated.hosts
> > /web/aes/admin/playbooks/split.yml -e ENV=qa -e NODE=cluster -e
> > instance_name=APP1,APP2
> >
> > Playbook:
> >
> > ---
> > - hosts: "{{ [ENV] | product(instance_name.split(',')) | product([NODE]) |
> > product(['wladmin_mmsplit'])|map('flatten')|map('join', '_') }}"

Put the logic into the inventory plugin *constructed*. See
shell> ansible-doc -t inventory ansible.builtin.constructed

In the example below, I'll use another inventory plugin *generator*
which you don't need because you obviously have another source of the
inventory. When you try the code below in your environment use this
source instead of 02-generator.yml. See
shell> ansible-doc -t inventory ansible.builtin.generator

I've ignored the case of the parameters.

1) Create the inventory

shell> tree inventory/
inventory/
├── 01-hosts
├── 02-generator.yml
└── 03-constructed.yml

shell> cat inventory/01-hosts 
localhost

shell> cat inventory/02-generator.yml 
plugin: ansible.builtin.generator
hosts:
  name: "{{ env }}_{{ instance }}_{{ node }}_{{ ext }}"
layers:
  env:
- dev
- qa
- prod
  instance:
- app1
- app2
  node:
- cluster1
- cluster2
  ext:
- wladmin_mmsplit

shell> cat inventory/03-constructed.yml 
plugin: ansible.builtin.constructed
use_extra_vars: true
compose:
  layer_env: ENV.split(',')
  layer_node: NODE.split(',')
  layer_instance: instance_name.split(',')
groups:
  my_group: inventory_hostname.split('_').0 in layer_env and
inventory_hostname.split('_').1 in layer_instance and
inventory_hostname.split('_').2 in layer_node

2) Test inventory

shell> ansible-inventory -i inventory --list --yaml
all:
  children:
ungrouped:
  hosts:
dev_app1_cluster1_wladmin_mmsplit: {}
dev_app1_cluster2_wladmin_mmsplit: {}
dev_app2_cluster1_wladmin_mmsplit: {}
dev_app2_cluster2_wladmin_mmsplit: {}
localhost: {}
prod_app1_cluster1_wladmin_mmsplit: {}
prod_app1_cluster2_wladmin_mmsplit: {}
prod_app2_cluster1_wladmin_mmsplit: {}
prod_app2_cluster2_wladmin_mmsplit: {}
qa_app1_cluster1_wladmin_mmsplit: {}
qa_app1_cluster2_wladmin_mmsplit: {}
qa_app2_cluster1_wladmin_mmsplit: {}
qa_app2_cluster2_wladmin_mmsplit: {}

3) Test inventory group *my_group*

shell> ansible-inventory -i inventory --list --yaml -e ENV=qa -e NODE=cluster2 
-e instance_name=app1,app2
all:
  children:
my_group:
  hosts:
qa_app1_cluster2_wladmin_mmsplit:
  ENV: qa
  NODE: cluster2
  instance_name: app1,app2
  layer_env:
  - qa
  layer_instance:
  - app1
  - app2
  layer_node:
  - cluster2
qa_app2_cluster2_wladmin_mmsplit:
  ENV: qa
  NODE: cluster2
  instance_name: app1,app2
  layer_env:
  - qa
  layer_instance:
  - app1
  - app2
  layer_node:
  - cluster2
ungrouped:
  hosts:
dev_app1_cluster1_wladmin_mmsplit:
...

4) Use *my_group* in a playbook

shell> cat pb.yml 
- hosts: my_group
  tasks:
- debug:
var: ansible_play_hosts_all
  run_once: true

shell> ansible-playbook -i inventory -e ENV=qa -e NODE=cluster2 -e 
instance_name=app1,app2 pb.yml

PLAY [my_group]
*

TASK [debug]
*
ok: [qa_app1_cluster2_wladmin_mmsplit] =>
  ansible_play_hosts_all:
  - qa_app1_cluster2_wladmin_mmsplit
  - qa_app2_cluster2_wladmin_mmsplit
  ...

5) The items added to the inventory (02-generator.yml in this example)

  instance:
- app1
- app2
- app3-brazil

will be automatically available for selection

shell> ansible-playbook -i inventory -e ENV=qa -e NODE=cluster2 -e 
instance_name=app1,app3-brazil pb.yml

PLAY [my_group]
**

TASK [debug]
*
ok: [qa_app1_cluster2_wladmin_mmsplit] => ansible_play_hosts_all:
  - qa_app1_cluster2_wladmin_mmsplit
  - qa_app3-brazil_cluster2_wladmin_mmsplit
  ...

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221228041926.7c027306%40gmail.com.


pgpsNUXdPi3Vw.pgp
Description: OpenPGP digital signature


Re: [ansible-project] How to split string twice in ansible playbook hosts section.

2022-12-27 Thread Vladimir Botka
On Tue, 27 Dec 2022 09:47:57 -0700
Richard Megginson  wrote:

> `split` is not an ansible filter

Wrong. The filter *split* is available since 2.11. See
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_filters.html#manipulating-strings

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221227192459.2011e8f0%40gmail.com.


pgpiQOqAKtbmU.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Lineinfile - Skip/Update an item inside "with_items" using conditions

2022-12-21 Thread Vladimir Botka
On Wed, 21 Dec 2022 16:30:03 +0500
farrukh ahmed  wrote:

> blockinfile:
> path: "{{ini_file_path}}" # set in defaults
> marker: ";# {mark} ANSIBLE MANAGED BLOCK ###"
> block: "{{ item.param }}"
> loop:
> - { param: "display_errors = {{service_configurations.display_errors |
> d(omit) }}"}
> - { param: "memory_limit = {{service_configurations.memory_limit | d(omit)
> }}M"}
> when: item.param is not search(omit)

The *marker* must be unique for each block. Otherwise the the blocks
will overwrite each other. For this purpose it would be practical to
change the structure of the iterated data. For example, the
simplified playbook below

  shell> cat pb.yml
  - hosts: localhost
tasks:
  - blockinfile:
  path: /tmp/test.ini
  marker: "# {mark} {{ item.param }}"
  block: |
{{ item.param }} = {{ item.value }}
loop:
  - param: 'display_errors'
value: "{{ conf.errors }}"
  - param: 'memory_limit'
value: "{{ conf.limit }}"

shell> ansible-playbook pb.yml -e '{"conf":{"errors":"On","limit":"128"}}'

works as expected and creates the file

  shell> cat /tmp/test.ini 
  # BEGIN display_errors
  display_errors = On
  # END display_errors
  # BEGIN memory_limit
  memory_limit = 128
  # END memory_limit

Fit the data and *marker* to your needs.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221221161421.22127660%40gmail.com.


pgpcmZo_YKoO_.pgp
Description: OpenPGP digital signature


Re: [ansible-project] at - specific time & date

2022-12-13 Thread Vladimir Botka
On Tue, 13 Dec 2022 15:15:06 +0100 (CET)
dulhaver via Ansible Project  wrote:

> > Yes, it's worth PR. I'll write tests for this. The question is which
> > collection?
> 
> 
> honestly, I am still not really 100% sure what the term
> 'collection' actually means in the Ansible context and how things
> are organized. The issue, however, lives in
> ansible-collection/ansible.posix. Isn't that hint enough?

I'm not sure if this kind of datetime conversion belongs to POSIX.

To learn about collections see https://github.com/ansible-collections

For example, Ansible.Posix, where the module ansible.posix.at comes
from, is "Ansible Collection targeting POSIX and POSIX-ish platforms."
https://docs.ansible.com/ansible/latest/collections/ansible/posix/index.html


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221213155643.7a48cea6%40gmail.com.


pgpRbwAkotuZb.pgp
Description: OpenPGP digital signature


Re: [ansible-project] at - specific time & date

2022-12-13 Thread Vladimir Botka
> count: "{{ at_datetime|at_minutes }}"
> ...
> would it be worth a PR on the issue or is this too quick'n'dirty? 

It's quick'n'clean I'd say :)

Yes, it's worth PR. I'll write tests for this. The question is which
collection?

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221213132000.59eb4000%40gmail.com.


pgpGVDMiFBB_w.pgp
Description: OpenPGP digital signature


Re: [ansible-project] at - specific time & date

2022-12-13 Thread Vladimir Botka
On Tue, 13 Dec 2022 09:23:40 +0100 (CET)
dulhaver via Ansible Project  wrote:

> thx that really works. It is not really user-friendly though.
> 
> Apparently I am not the only one thinking this should be easier, so there is 
> an issue for adding a more intuitive way to specify time and date 
> https://github.com/ansible-collections/ansible.posix/issues/326

> > now_datetime: "{{ '%Y-%m-%d %H:%M:%S'|strftime }}"
> > at_datetime: "2022-12-12 17:30:00"
> > at_seconds: "{{ ((at_datetime|to_datetime) -
> >  (now_datetime|to_datetime)).seconds }}"
> > at_minutes: "{{ (at_seconds|int / 60)|int + 1 }}"
> > 
> > - ansible.posix.at:
> > command: date > /tmp/test_at
> > count: "{{ at_minutes }}"
> > units: minutes

Yes, it's rather awkward. I simplified the declaration of
*at_seconds*. It might be a good idea to have a conversion function
for this, e.g.


- ansible.posix.at:
command: date > /tmp/test_at
count: "{{ at_datetime|at_minutes }}"
units: minutes
  vars:
at_datetime: "2022-12-12 17:30:00"
  

Try

shell> cat plugins/filter/at_minutes.py
from datetime import datetime


def at_minutes(at_datetime):
timesince = datetime.fromisoformat(at_datetime) - datetime.now()
return int(timesince.total_seconds() / 60 + 1)


class FilterModule(object):

def filters(self):
return {
'at_minutes': at_minutes,
}


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221213110300.52f9ca3e%40gmail.com.


pgp4WQz0aegz5.pgp
Description: OpenPGP digital signature


Re: [ansible-project] at - specific time & date

2022-12-12 Thread Vladimir Botka
On Mon, 12 Dec 2022 15:30:07 +0100 (CET)
dulhaver via Ansible Project  wrote:

> I want to automate a list of command exections with at.
> What is the concepts here to specify something like '16:00 2023-01-19'?

For example, to schedule a command at "2022-12-12 17:30:00" declare
the variables

now_datetime: "{{ '%Y-%m-%d %H:%M:%S'|strftime }}"
at_datetime: "2022-12-12 17:30:00"
at_seconds: "{{ ((at_datetime|to_datetime) -
 (now_datetime|
  to_datetime('%Y-%m-%d %H:%M:%S'))).seconds }}"
at_minutes: "{{ (at_seconds|int / 60)|int + 1 }}"

gives

now_datetime: 2022-12-12 17:26:23
at_datetime: 2022-12-12 17:30:00
at_seconds: 217
at_minutes: 4

Use the variable *at_minutes*

- ansible.posix.at:
command: date > /tmp/test_at
count: "{{ at_minutes }}"
units: minutes
- command: at -l
  register: out
- debug:
var: out.stdout

will display the queue

  out.stdout: "5\tMon Dec 12 17:30:00 2022 a admin"

The command executed as expected

shell> cat /tmp/test_at 
Mon 12 Dec 2022 05:30:00 PM CET

Example of a complete playbook for testing

- hosts: localhost

  vars:

now_datetime: "{{ '%Y-%m-%d %H:%M:%S'|strftime }}"
at_datetime: "2022-12-12 17:30:00"
at_seconds: "{{ ((at_datetime|to_datetime) -
 (now_datetime|
  to_datetime('%Y-%m-%d %H:%M:%S'))).seconds }}"
at_minutes: "{{ (at_seconds|int /
60)|int + 1 }}"

  tasks:

- debug:
msg: |
  now_datetime: {{ now_datetime }}
  at_datetime: {{ at_datetime }}
  at_seconds: {{ at_seconds }}
  at_minutes: {{ at_minutes }}

- ansible.posix.at:
command: date > /tmp/test_at
count: "{{ at_minutes }}"
units: minutes

- command: at -l
  register: out

- debug:
var: out.stdout

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221212173718.597130f3%40gmail.com.


pgpzoGGh0CP7_.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Question about authorized_key module

2022-12-07 Thread Vladimir Botka
On Wed, 7 Dec 2022 12:23:59 -0800 (PST)
"lift...@gmail.com"  wrote:

> - hosts: rhev_hosts
>   become: yes
>   become_method: su
>   gather_facts: no
>   vars:
> ssh_key: '/root/.ssh/id_rsa.pub'
> 
>   tasks:
> 
>   - name: Copy SSH key to each server
> authorized_key:
>   key: "{{ lookup('file', ssh_key) }}"
>   user: root
> 
> Will that basically do an ssh-copy-id from each host in rhev_hosts to 
> every other host in that host group?

No. The playbook won't neither do *ssh-copy-id* nor will it copy
public keys from each host in rhev_hosts to every other host in that
host group. The playbook will read /root/.ssh/id_rsa.pub on the
controller and insert this public key into the root's authorized_key
file on each host in the group rhev_hosts.

Notes:
* lookup always works on the controller.
* It is a bad idea to use root account on the Ansible controller to
  run a playbook. 
* It is also a bad idea to ssh to root on the remote host.
* The module ansible.posix.authorized_key doesn't use *ssh-copy-id*
  utility. It writes the file authorized_key directly.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221207221833.2fef2968%40gmail.com.


pgpWba4gzGMdL.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Identify most recent directory in a directory.

2022-12-01 Thread Vladimir Botka
Use Ansible module *find* and sort the directories by *ctime*. For
example, given the tree

shell> tree /tmp/test
/tmp/test
├── 2022-12-01_1701
├── 2022-12-01_1702
└── 2022-12-01_1703

Declare the variable

  last_dir: "{{ (out.files|sort(attribute='ctime')|last).path }}"

The tasks below

- find:
path: /tmp/test
file_type: directory
  register: out
- debug:
var: last_dir

give

  last_dir: /tmp/test/2022-12-01_1703

If you want to take look at the *ctime*

  path_ctime: "{{ out.files|json_query('[].[path, ctime]') }}"

give

  path_ctime:
- [/tmp/test/2022-12-01_1702, 1669938403.313556]
- [/tmp/test/2022-12-01_1701, 1669938401.2335565]
- [/tmp/test/2022-12-01_1703, 1669938405.0495553]

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221202011038.0ed02422%40gmail.com.


pgpuhZVpCLY4r.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Special variable group_names list items out of order

2022-11-03 Thread Vladimir Botka
On Thu, 3 Nov 2022 03:57:19 -0700 (PDT)
Goran Kuzmanović  wrote:

> https://github.com/ansible/ansible/issues/73208 when the explanation 
> provided was "The group_names variable is purposefully alphanumerically 
> sorted by name, and not sorted by definition order." ... get the list 
> of groups on which you can rely, level-wise ?

Use *ansible-inventory* and parse the inventory on your own. Given
the example from the issue

shell> cat hosts
all:
  children:
NonprodAppDefault:
  children:
CHG0240322:
  vars:
controller_env: test
  hosts:
hdqqclansiap001:
hdqqclbcbwtb001:


1) Declare the variables

inventory: "{{ out.stdout|from_yaml }}"
my_groups: {}
my_groups_0: "{{ inventory.all.children }}"

2) Parse the inventory

- command: ansible-inventory --list --yaml
  register: out

gives

  inventory:
all:
  children:
NonprodAppDefault:
  children:
CHG0240322:
  hosts:
hdqqclansiap001:
  controller_env: test
hdqqclbcbwtb001:
  controller_env: test
ungrouped: {}

3) Create the dictionary of your groups

- set_fact:
my_groups: "{{ my_groups|
   combine({item: _groups}) }}"
  loop: "{{ my_groups_0.keys()|list }}"
  vars:
_groups: "{{ (my_groups_0[item].children|
  default({})).keys()|list }}"


gives (probably what you want)

  my_groups:
    NonprodAppDefault:
- CHG0240322
ungrouped: []


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221103155539.740d0389%40gmail.com.


pgplg59gGHEsu.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Looking for alternative to set_fact + loop

2022-10-11 Thread Vladimir Botka
On Tue, 11 Oct 2022 16:05:42 +0200
Dick Visser  wrote:

> list structure that is defaulted to a single (dict) item ...
> additional items use the keys of the first item as their default.

For example, given the default dictionary and the extra list

defaults:
  name: default
  desc: standard
  foo: true
  bar: true

extra:
  - name: foobar
desc: dedicated
  - name: noli
desc: discovery

the declaration below

discos: "{{ [defaults] +
[defaults]|product(extra)|map('combine')|list }}"

gives the expected list

  discos:
  - bar: true
desc: standard
foo: true
name: default
  - bar: true
desc: dedicated
foo: true
name: foobar
  - bar: true
desc: discovery
foo: true
name: noli

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20221011175709.189ee983%40gmail.com.


pgpSJiTRJybHe.pgp
Description: OpenPGP digital signature


Re: [ansible-project] populating dictionary from lookup

2022-09-29 Thread Vladimir Botka
The next option is putting the iteration into one task. For example,

- set_fact:
soarecords_dict: "{{ soarecords_dict|d({})|
 combine({item: _dict}) }}"
  loop: "{{ zones }}"
  vars:
_dict: "{{ dict(soafields|
   zip(lookup('dig', item, 'qtype=SOA')|split)) }}"


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220929231757.660a4999%40gmail.com.


pgp79kaSj20Ki.pgp
Description: OpenPGP digital signature


Re: [ansible-project] populating dictionary from lookup

2022-09-29 Thread Vladimir Botka
Create it in Jinja. For example,

soarecords: |
  {% for zone in zones %}
  {{ zone }}:
  {% for field in lookup('dig', zone, 'qtype=SOA')|split %}
{{ soafields[loop.index0] }}: {{ field }}
  {% endfor %}
  {% endfor %}
soarecords_dict: "{{ soarecords|from_yaml }}"

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220929230403.4de13028%40gmail.com.


pgp884lEqybqg.pgp
Description: OpenPGP digital signature


Re: [ansible-project] create variable from value gathered on remote

2022-09-19 Thread Vladimir Botka
On Mon, 19 Sep 2022 12:23:14 +0200 (CEST)
dulhaver via Ansible Project  wrote:

> ... does not localize the files I am looking for.
> 
>- name: fetch all .env files to fetched
>  ansible.builtin.fetch:
>src: /opt/db/postgres/bin/.pg*env
>dest: fetched/
>flat: true
>  become: yes

Find the files first. See
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/find_module.html

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220919123422.2b2f5b23%40gmail.com.


pgpCAuNUyeGFc.pgp
Description: OpenPGP digital signature


Re: [ansible-project] create variable from value gathered on remote

2022-09-16 Thread Vladimir Botka
For example, given the files

shell> ssh admin@test_11 cat /tmp/.env
SMTPPORT: 5432
POPPORT: 5431
PGPORT: 5433

shell> ssh admin@test_12 cat /tmp/.env
SMTPPORT: 4432
POPPORT: 4431
PGPORT: 4433

shell> ssh admin@test_13 cat /tmp/.env
SMTPPORT: 3432
POPPORT: 3431
PGPORT: 3433

Fetch the files and declare the variables you need

shell> cat pb.yml
- hosts: test_11,test_12,test_13
  vars:
env_file: /tmp/.env
env_dest: "{{ playbook_dir }}/env_dest"
my_env_file: "{{ [env_dest, inventory_hostname, env_file]|
 join('/') }}"
my_ports: "{{ lookup('file', my_env_file)|from_yaml }}"
pg_service_port: "{{ my_ports.PGPORT + 1 }}"
  tasks:
- fetch:
src: "{{ env_file }}"
dest: "{{ env_dest }}"
- debug:
var: pg_service_port

give (abridged)

ok: [test_11] => 
  pg_service_port: '5434'
ok: [test_12] => 
  pg_service_port: '4434'
ok: [test_13] => 
  pg_service_port: '3434'

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220916184429.2cc0a3a3%40gmail.com.


pgpfcnV3G_KVu.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Ansible dict date to csv file

2022-09-10 Thread Vladimir Botka
Create the list. Put the below declarations into *vars*

  csv_query: '[].[`Clusters`, key, value[].node, value[].state]'
  csv: "{{ Clusters|dict2items|json_query(csv_query)|
   map('flatten')|map('join', ',')|list }}"

gives

  csv:
  - Clusters,192.168.1.1,node1,up
  - Clusters,192.168.1.2,node2,down
  - Clusters,192.168.1.3,node3,up

Write the file

  - copy:
  dest: /tmp/Clusters.csv
  content: "{{ csv|join('\n') }}"

gives

shell> cat /tmp/Clusters.csv 
Clusters,192.168.1.1,node1,up
Clusters,192.168.1.2,node2,down
Clusters,192.168.1.3,node3,up

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220910200420.1fc88026%40gmail.com.


pgpujfFm96WBf.pgp
Description: OpenPGP digital signature


Re: [ansible-project] ansible --check mode for shift left

2022-09-07 Thread Vladimir Botka
On Wed, 7 Sep 2022 08:36:14 -0700 (PDT)
Steve Button  wrote:

Providing default values for missing outputs might be a better option
in some cases. It would be good to see the particular case(s).


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220907175904.406218a0%40gmail.com.


pgp0TZWBD1XIW.pgp
Description: OpenPGP digital signature


[ansible-project] was: passing "var" from one playbook to another playbook

2022-08-24 Thread Vladimir Botka
On Wed, 24 Aug 2022 11:11:56 +
"'Rowe, Walter P. (Fed)' via Ansible Project"
 wrote:

> ... This only works in Ansible Tower. It won't work from the command line.  

Walter,

what exactly is the functionality provided by Tower only?

Thank you,

Best regards

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220824163109.41d12c68%40gmail.com.


pgpyyypDImWOZ.pgp
Description: OpenPGP digital signature


Re: [ansible-project] variable not defined

2022-08-24 Thread Vladimir Botka
On Wed, 24 Aug 2022 05:05:14 -0700 (PDT)
Kenady Inampudi  wrote:

>   tasks:
> - getent:
> database: passwd
> key: ^ora.*$'
>   register: userid
>   ignore_errors: true
> - command: "id {{ item }}"
>   register: id
>   loop: "{{ userid.stdout_lines }}"
> - debug:
> msg: "{{ id.results|map(attribute='stdout')|list }}"

Try

- hosts: node1.example.com
  gather_facts: false
  vars:
users: "{{ getent_passwd.keys()|list }}"
  tasks:
- getent:
database: passwd
- command: "id {{ item }}"
  register: id
  loop: "{{ users|select('match', '^user.*$') }}"
- debug:
msg: "{{ id.results|map(attribute='stdout')|list }}"

Notes:

* The module *getent* stores the data automagically. In the case of
  *passwd* the dictionary will be *getent_passwd*

* Put the declaration of *users* into vars

* Fit the regex to your needs and iterate the selected users

* The debug of the results is the same as before

* Take a look at *getent_passwd*

* The same way you can get the content of /etc/group in the
  dictionary *getent_group*

* You can create any structure you like when you have both
  dictionaries *getent_passwd* and *getent_group*


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220824143235.292f328d%40gmail.com.


pgp8mlG4EgXOn.pgp
Description: OpenPGP digital signature


Re: [ansible-project] passing "var" from one playbook to another playbook

2022-08-24 Thread Vladimir Botka
On Wed, 24 Aug 2022 11:11:56 +
"'Rowe, Walter P. (Fed)' via Ansible Project"
 wrote:

> ... This only works in Ansible Tower. It won't work from the command line.

What exactly is the functionality provided by Tower only?

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220824135818.54779017%40gmail.com.


pgpvvE5JvjUYP.pgp
Description: OpenPGP digital signature


Re: [ansible-project] variable not defined

2022-08-24 Thread Vladimir Botka
On Wed, 24 Aug 2022 02:17:38 -0700 (PDT)
Kenady Inampudi  wrote:

> - shell: id "{{ item }}"
>   register: id
>   with_items: "{{ userid.stdout.split('\n') }}"
> - debug:
> var: id.stdout_lines

The variable *id* was registered in a loop. You need the attribute
*results*. (Take a look at *id*.)

Try

- debug:
msg: "{{ id.results|map(attribute='stdout')|list }}"


Notes:

* Use *getent* instead of reading /etc/passwd* on your own
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/getent_module.html

* Use *command* instead of *shell*, *loop* instead of *with_items*,
  and *userid.stdout_lines* instead of *userid.stdout.split('\n')*

- command: "id {{ item }}"
  register: id
  loop: "{{ userid.stdout_lines }}"

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220824123753.15430d86%40gmail.com.


pgpxYhl8iAPV7.pgp
Description: OpenPGP digital signature


Re: [ansible-project] I am curious about ~/.ansible vs ~/ansible - why was that done?

2022-08-23 Thread Vladimir Botka
On Tue, 23 Aug 2022 03:56:29 -0400
Nico Kadel-Garcia  wrote:

> On Tue, Aug 23, 2022 at 12:23 AM Jeff Silverman  wrote:
> >
> > ... Why .ansible, which is hidden, and not ansible, which is not
> > hidden? ... why did the ansible designers elect to use a hidden
> > directory? They were/are very smart people, so they must have had
> > a good reason, what was it?

The main reason is that this directory keeps configuration files. The
justification for having hidden files is that if you don't see them,
you are less likely to damage them.

But, generally, you're right. The concept of a hidden file was an
unintended consequence. It was certainly a mistake.
https://linux-audit.com/linux-history-how-dot-files-became-hidden-files/

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220823112231.42981750%40gmail.com.


pgpnYHlJ7BkOQ.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Error- When Condition

2022-08-13 Thread Vladimir Botka
On Sat, 13 Aug 2022 17:58:02 -0400
Nico Kadel-Garcia  wrote:

> On Fri, Aug 12, 2022 at 2:48 AM Vladimir Botka  wrote:
> >
> > On Fri, 12 Aug 2022 11:01:01 +0500
> > farrukh ahmed  wrote:
> >  
> > > *What I'm trying to achieve is that;*
> > > *1) Check if any job process is running.*
> > > *2) If the job process found running then; first stop the process and then
> > > remove the process.*  
> >
> > Use *pkill*
> > https://www.commandlinux.com/man-page/man1/pkill.1.html
> 
> pkill is a useful tool, and a dangerous one if other processes may
> have matching names. Use it cautiously.

Right. Probably it would be good to add that cautious usage here
includes running *pgrep* first and see whether the selected processes
are what you really want. This is the reason why *pgrep/pkill* come
together.

FWIW. See the playbook for testing asynchronous scripts and signals
https://gist.github.com/vbotka/755c3c4fea3d7afb54406412325a3f12


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220814014019.7ee02329%40gmail.com.


pgp2DwgwJ2c6j.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Error- When Condition

2022-08-12 Thread Vladimir Botka
On Fri, 12 Aug 2022 11:01:01 +0500
farrukh ahmed  wrote:

> *What I'm trying to achieve is that;*
> *1) Check if any job process is running.*
> *2) If the job process found running then; first stop the process and then
> remove the process.*

Use *pkill*
https://www.commandlinux.com/man-page/man1/pkill.1.html

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220812084835.2c61b36e%40gmail.com.


pgpoPmq4HgynN.pgp
Description: OpenPGP digital signature


Re: [ansible-project] How to extract a specific value from input list ?

2022-08-09 Thread Vladimir Botka
On Tue, 9 Aug 2022 05:09:41 -0700 (PDT)
"'Walter Rowe' via Ansible Project"
 wrote:

> You also can use json_query. 

For example, the template

shell> cat templates/server.xml.j2
insights.jdbc.password="{{ my_pswd }}"

and the task

- debug:
msg: "{{ lookup('template', 'server.xml.j2') }}"
  vars:
my_user: user4
my_pswd: "{{ postgres_create_users|
 json_query(_query)|first }}"
_query: '[?role==`{{ my_user }}`].password'

gives the same result

TASK [debug]
**
ok: [localhost] => msg: |-
    insights.jdbc.password="password4"

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220809150110.1f2bd3c9%40gmail.com.


pgpG3mxmTxod9.pgp
Description: OpenPGP digital signature


Re: [ansible-project] How to extract a specific value from input list ?

2022-08-09 Thread Vladimir Botka
On Mon, 8 Aug 2022 23:07:32 -0700 (PDT)
"dudu.c...@gmail.com"  wrote:

> insights.jdbc.password={{ postgres_create_users ??? }}

Create a dictionary. The best choice might be the same place the list
*postgres_create_users* comes from. For example,

shell> cat group_vars/all/postgres_create_users.yml 
postgres_create_users:
  - {role: user1, password: password1}
  - {role: user2, password: password2}
  - {role: user3, password: password3}
  - {role: user4, password: password4}
pcu_dict: "{{ postgres_create_users|
  items2dict(key_name='role',
 value_name='password') }}"

gives

  pcu_dict:
user1: password1
user2: password2
user3: password3
user4: password4

The usage is trivial. For example, the template

shell> cat templates/server.xml.j2
insights.jdbc.password="{{ pcu_dict.user4 }}"

and the playbook

shell> cat pb.yml
- hosts: localhost
  tasks:
- debug:
msg: "{{ lookup('template', 'server.xml.j2') }}"

gives (abridged)

shell> ansible-playbook pb.yml

TASK [debug]
**
ok: [localhost] => msg: |-
insights.jdbc.password="password4"

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220809124859.314feda9%40gmail.com.


pgpBBJGey_g2J.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Lineinfile - Skip/Update an item inside "with_items" using conditions

2022-08-05 Thread Vladimir Botka
On Thu, 4 Aug 2022 23:43:59 -0700 (PDT)
farrukh ahmed  wrote:

> with_items:
>   - { regexp: '^text1', line: "text1 = {{ VAR1 }}", when: VAR1 is defined }
>   - { regexp: '^text2', line: "text2 = {{ VAR2 }}" }
>   - { regexp: '^text3', line: "text3 = {{ VAR3 }}" }

Set *default* to avoid errors, add attribute *def*, and select lines.
For example,

shell> cat pb.yml
---
- hosts: localhost
  gather_facts: false
  vars:
lines:
  - regexp: '^text1'
line: 'text1 = {{ VAR1|d("undef") }}'
def: '{{ VAR1 is defined }}'
  - regexp: '^text2'
line: 'text2 = {{ VAR2|d("undef") }}'
def: '{{ VAR2 is defined }}'
  - regexp: '^text3'
line: 'text3 = {{ VAR3|d("undef") }}'
def: '{{ VAR3 is defined }}'
  tasks:
- debug:
var: item
  loop: "{{ lines|selectattr('def') }}"

gives

shell> ansible-playbook pb.yml -e VAR1=test

PLAY [localhost]
*

TASK [debug]
*
ok: [localhost] => (item={'regexp': '^text1', 'line': 'text1 = test',
'def': True}) => ansible_loop_var: item item:
def: true
line: text1 = test
regexp: ^text1

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220805111742.55c17fbf%40gmail.com.


pgpZj2RZv0VfV.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Re: Pull of List in a Variable File as Extra-Vars

2022-08-04 Thread Vladimir Botka
> On Wednesday, August 3, 2022 at 5:02:16 PM UTC-4 wpgpo...@gmail.com wrote:
> > *general_var.yml*
> > main_dir: "{{ app_name }}-{{ ansible_hostname }}-{{ ver }}"

Use *vars* lookup plugin to indirectly reference the value of the
variable stored in *app_name*. Then use filter *product* to create
the combinations. For example, given

* the extra variable '-e app_name=dir_list'
* the variable *dir_list*
  shell> cat dirname.yml
  dir_list:
- hello
- goodbye
- take-care
* the inventory
  shell> cat hosts
  host01 ansible_hostname=01.us.com
* the variable 'ver=123'

The variable *main_dir*

  shell> cat general_var.yml
  main_dir: "{{ lookup('vars', app_name)|
product([ansible_hostname])|
product([ver])|
map('flatten')|
map('join','-')|list }}"

gives the list you want (simplified)

  main_dir:
- hello-01.us.com-123
- goodbye-01.us.com-123
- take-care-01.us.com-123

Test the iteration

- debug:
msg: "copy {{ item.0 }} to {{ item.1 }}"
  with_nested:
- "{{ patch_lib }}"
- "{{ main_dir }}"

gives (abridged)

  msg: copy lib_1 to hello-01.us.com-123
  msg: copy lib_1 to goodbye-01.us.com-123
  msg: copy lib_1 to take-care-01.us.com-123
  msg: copy lib_2 to hello-01.us.com-123
  msg: copy lib_2 to goodbye-01.us.com-123
  msg: copy lib_2 to take-care-01.us.com-123

Fit the details to your needs.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220805023513.6c198a2e%40gmail.com.


pgppE4yuS_wdF.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Help with complex json_query

2022-08-03 Thread Vladimir Botka
On Wed, 3 Aug 2022 14:29:27 -0700 (PDT)
"spiro.m...@mcgill.ca"  wrote:

>  - debug:
>   msg: "{{ item.fvAEPg.attributes.name }} is in app profile: {{ 
> application_profiles | to_json | from_json | 
> json_query('*.[?epg_name.contains(@, `{{ item.fvAEPg.attributes.name 
> }}`)].app_name') }}"
> loop: "{{ epg_bd_list }}"

Try this:

  - debug:
  msg: "{{ _item }} is in app profile: {{ app_profile }}"
loop: "{{ epg_bd_list }}"
vars:
  _item: "{{ item.fvAEPg.attributes.name }}"
  _query: '[?epg_name.contains(@, `{{ _item }}`)].app_name'
  app_profile: "{{ application_profiles|json_query(_query) }}"


Note: In the JSON, the braces {} are not properly balanced. Use YAML

  application_profiles:
- app_desc: ''
  app_name: NCS_Net_inf
  epg_name:
- SPAN-destination-analysis
- infra_auth_servers
- netinf_test_servers
- paaa-infra-mgt
- vl2003
- app_desc: 'dept: MedIT'
  app_name: faculty_of_medicine
  epg_name:
- medit_jump_server
- app_desc: ''
  app_name: dc_qa_app_fe
  epg_name:
- vl3800

  epg_bd_list:
- fvAEPg:
attributes:
  name: SPAN-destination-analysis
  nameAlias: vl2022
- fvAEPg:
    attributes:
  name: vl72
  nameAlias: Bone_Centre

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220804065141.5d1a20eb%40gmail.com.


pgpaW18ZrzlhU.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Speeding up a task

2022-07-30 Thread Vladimir Botka
On Sat, 30 Jul 2022 17:44:12 +0700
Ian Hobson  wrote:

> - name: "restore files to {{ location }}"
>ansible.builtin.copy:
>  src:  "/home/ian/backup/hobson42/var/www/ianhobson.com/"
>  dest: "{{ location }}"
> 
> It copies 5022 files, totalling 109.2Mb, and even though both machines 
> have NVME SSDs and the network is quiet,
> the task takes over 30 minutes!

Use module *ansible.posix.synchronize* if you can install *rsync*
both on local and remote host. See
https://docs.ansible.com/ansible/latest/collections/ansible/posix/synchronize_module.html

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220730125526.0b559bad%40gmail.com.


pgpq4hMYoHfsw.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Hooks in Ansible

2022-07-26 Thread Vladimir Botka
On Tue, 26 Jul 2022 07:32:33 +0200
Daniel Gonçalves  wrote:

> context: I have a custom lookup plugin that 
> initialize some data and execute a new process ... 
> I want to be able to send a SIGTERM signal to the process to
> terminate it at the end of playbook execution.

This seems to be a candidate for *async*
https://docs.ansible.com/ansible/latest/user_guide/playbooks_async.html#run-tasks-concurrently-poll-0

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220726105716.3a28b244%40gmail.com.


pgp1Zce6zqa6k.pgp
Description: OpenPGP digital signature


Re: [ansible-project] Hooks in Ansible

2022-07-25 Thread Vladimir Botka
On Mon, 25 Jul 2022 19:06:33 +0200
Daniel Gonçalves  wrote:

> What I want to do is executing some code at the end of the playbook 
> execution, in other words executing some code at some arbitrary playbook 
> execution step. I wonder if there is some event listener I can subscribe 
> on in order to execute my code.

This depends on the use case:

1) To execute the code at the end of the playbook you can use
   *post_tasks*. At some arbitrary playbook execution step use
   *tasks*.

2) To trigger the execution of a code by some events you can use
   the module *wait_for*
   
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/wait_for_module.html#ansible-builtin-wait-for-module-waits-for-a-condition-before-continuing
   and *handlers*
   https://docs.ansible.com/ansible/latest/user_guide/playbooks_handlers.html

3) To execute the code after the playbook finished you can use
   *ansible-runner*
   
https://ansible-runner.readthedocs.io/en/stable/python_interface/#usage-examples


-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220725215524.6aaab024%40gmail.com.


pgppsViJXWnql.pgp
Description: OpenPGP digital signature


Re: [ansible-project] display information returned with debug in a more usable layout

2022-07-20 Thread Vladimir Botka
On Wed, 20 Jul 2022 14:48:51 +0200 (CEST)
dulhaver via Ansible Project  wrote:

> I see there is a lot to learn and understand yet (in this case "use
> of variables" for example).

> > > - hosts: all
> > >   vars:
> > > ansible_user: gwagner
> > > ver: "{{ ansible_play_hosts|
> > >  map('extract', hostvars, ['backrest_version', 'stdout'])|
> > >  map('split', ' ')|map('last')|
> > >  list }}"
> > > pkg: "{{ dict(ansible_play_hosts|zip(ver)) }}"
> > > 
> > >   tasks:
> > > - name: check pgBackRest version
> > >   ansible.builtin.command: /usr/bin/pgbackrest version
> > >   register: backrest_version
> > > 
> > > - name: Print return information from the previous task
> > >   ansible.builtin.debug:
> > > var: backrest_version.stdout
> > >   when: debug|d(false)|bool
> > > 
> > > - name: Write the CSV file
> > >   ansible.builtin.copy:
> > > dest: pkg.csv
> > > content: |-
> > >   {% for k,v in pkg.items() %}
> > >   {{ k }},{{ v }}
> > >   {% endfor %}
> > >   delegate_to: localhost
> > >   run_once: true  

There are a couple of aspects.

* It's good to know that in Ansible the variables are evaluated at
  the last moment, aka "lazy evaluation".

* There are many places where you can declare variables. See
  
https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable

* Where would you like to use the variables? In your case, this is
  probably the best question to ask when you want to decide where to
  declare the variables. Put them into the playbook vars (above) if
  you want to use them in the whole playbook. If you need the
  variables to write the CSV file only put them into the task vars
  (below)

  - name: Write the CSV file
ansible.builtin.copy:
  dest: pkg.csv
  content: |-
{% for k,v in pkg.items() %}
{{ k }},{{ v }}
{% endfor %}
delegate_to: localhost
run_once: true  
vars:
  ver: "{{ ansible_play_hosts|
   map('extract', hostvars,
   ['backrest_version','stdout'])|map('split', ' ')|
   map('last')|
  list }}"
  pkg: "{{ dict(ansible_play_hosts|zip(ver)) }}"
 
  This limits the scope of the variables. See
  
https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#scoping-variables

* To make the code cleaner, you can put the variables into some files.
  For example into the group_vars,

  shell>  cat group_vars/all
  ansible_user: gwagner
  ver: "{{ ansible_play_hosts|
   map('extract', hostvars, ['backrest_version', 'stdout'])|
   map('split', ' ')|map('last')|
   list }}"
  pkg: "{{ dict(ansible_play_hosts|zip(ver)) }}"
  content: |-
{% for k,v in pkg.items() %}
{{ k }},{{ v }}
{% endfor %}

  This will simplify the playbook

  - hosts: all
    tasks:
  - name: check pgBackRest version
ansible.builtin.command: /usr/bin/pgbackrest version
register: backrest_version
  - name: Write the CSV file
ansible.builtin.copy:
  dest: pkg.csv
  content: "{{ content }}"
delegate_to: localhost
run_once: true  

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220720192931.1359b0fa%40gmail.com.


pgpBVYYVLGKnA.pgp
Description: OpenPGP digital signature


Re: [ansible-project] display information returned with debug in a more usable layout

2022-07-20 Thread Vladimir Botka
You're welcome. Put the declarations of *ver* and *pkg* into the
*vars*. I edited your code in-line


On Wed, 20 Jul 2022 13:48:40 +0200 (CEST)
Gunnar Wagner  wrote:

> - hosts: all
>   vars:
> ansible_user: gwagner
> ver: "{{ ansible_play_hosts|
>  map('extract', hostvars, ['backrest_version', 'stdout'])|
>  map('split', ' ')|map('last')|
>  list }}"
> pkg: "{{ dict(ansible_play_hosts|zip(ver)) }}"
> 
>   tasks:
> - name: check pgBackRest version
>   ansible.builtin.command: /usr/bin/pgbackrest version
>   register: backrest_version
> 
> - name: Print return information from the previous task
>   ansible.builtin.debug:
> var: backrest_version.stdout
>   when: debug|d(false)|bool
> 
> - name: Write the CSV file
>   ansible.builtin.copy:
> dest: pkg.csv
> content: |-
>   {% for k,v in pkg.items() %}
>   {{ k }},{{ v }}
>   {% endfor %}
>   delegate_to: localhost
>   run_once: true

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220720140300.0277131c%40gmail.com.


pgpObdQbgIFI7.pgp
Description: OpenPGP digital signature


  1   2   3   4   5   6   7   >