Execution
Date 11 Sep 2024 12:59:59 +0100
Duration 00:00:14.65
Controller ssh-gw-4.layershift.com
User root
Versions
Ansible 2.16.4
ara 1.7.1 / 1.7.1
Python 3.10.10
Summary
21 Hosts
10 Tasks
67 Results
3 Plays
6 Files
0 Records

File: /home/ssh-gateway/ansible/kuly/create9.yaml

---
- name: Manage inventory files
  hosts: localhost
  gather_facts: false
  vars:
    files:
      - /home/ssh-gateway/ansible/kuly/canary-inventory
      - /tmp/plesk_hosts.txt
  tasks:
    - name: Delete existing inventory and temp files
      ansible.builtin.file:
        path: "{{ item }}"
        state: absent
      loop: "{{ files }}"

    - name: Create inventory file and header
      ansible.builtin.lineinfile:
        path: /home/ssh-gateway/ansible/kuly/canary-inventory
        line: "[canary]\n"
        create: true
        mode: '0644'

- name: Collect Plesk hosts
  hosts: all
  gather_facts: false
  roles:
    - plesk
  tasks:
    - name: Save Plesk hostnames to a temp file
      when: plesk_found
      ansible.builtin.lineinfile:
        path: /tmp/plesk_hosts.txt
        line: "{{ inventory_hostname }}"
        create: true
        mode: '0644'
      delegate_to: localhost

- name: Process Plesk hosts
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Read Plesk hosts from file
      ansible.builtin.set_fact:
        plesk_hosts_content: "{{ lookup('file', '/tmp/plesk_hosts.txt') }}"

    - name: Select 10 random Plesk hosts
      ansible.builtin.set_fact:
        random_plesk_hosts: >
          {% set number_to_select = 10 %}
          {% set lines = plesk_hosts_content.split('\n') %}
          {% if lines | length > number_to_select %}
            {% set shuffled = lines | shuffle %}
            {{ shuffled[:number_to_select] }}
          {% else %}
            {{ lines }}
          {% endif %}

    - name: Format random Plesk hosts as a string with each host on a new line
      ansible.builtin.set_fact:
        random_plesk_hosts_str: |
          {% for host in random_plesk_hosts %}
          {{ host | trim() }}
          {% endfor %}

    - name: Save formatted random Plesk hosts to file
      ansible.builtin.copy:
        dest: /home/ssh-gateway/ansible/kuly/random_plesk_hosts.txt
        content: "{{ random_plesk_hosts_str }}"
        mode: '0644'

    - name: Write selected Plesk hosts to inventory file
      ansible.builtin.copy:
        dest: /home/ssh-gateway/ansible/kuly/canary-inventory
        content: |
          [canary]
          {% for host in random_plesk_hosts %}
          {{ host | trim() }}
          {% endfor %}
          [canary:vars]
          ansible_user=root
          ansible_port=2233
        mode: '0644'