Several changes to include SSHing as the proper user with the right key

This commit is contained in:
2025-08-07 13:36:33 -05:00
parent e07d000435
commit 0b0ae30967
4 changed files with 177 additions and 124 deletions

9
inventory/hosts Normal file
View File

@@ -0,0 +1,9 @@
[local]
localhost ansible_connection=local
[linode:children]
# Dynamic groups will be populated by the inventory script
[all:vars]
ansible_user=phlux
ansible_ssh_common_args='-o StrictHostKeyChecking=no'

View File

@@ -97,6 +97,7 @@ class LinodeInventory:
linode_tags = instance.get('tags', []) linode_tags = instance.get('tags', [])
inventory['_meta']['hostvars'][hostname] = { inventory['_meta']['hostvars'][hostname] = {
'ansible_host': primary_ip, 'ansible_host': primary_ip,
'ansible_user': 'phlux', # Set default SSH user
'linode_id': instance['id'], 'linode_id': instance['id'],
'linode_label': instance['label'], 'linode_label': instance['label'],
'linode_region': instance['region'], 'linode_region': instance['region'],

View File

@@ -1,139 +1,182 @@
--- ---
# Main tasks for linode_inventory role - name: Update Linode Dynamic Inventory
hosts: localhost
gather_facts: true
connection: local
- name: Set API token (AWX credential injection takes precedence) vars:
ansible.builtin.set_fact: # Override these variables as needed
linode_api_token: "{{ linode_api_token | default(lookup('env', 'LINODE_API_TOKEN')) | default('') }}" linode_inventory_output_dir: "/tmp/linode_inventory"
inventory_format: "json" # or "ini"
awx_integration: true
cleanup_temp_files: false
- name: Validate required variables # Optional filters
ansible.builtin.assert: include_only_running: false
that: specific_regions: [] # e.g., ['us-east', 'us-west']
- linode_api_token is defined specific_tags: [] # e.g., ['production', 'web']
- linode_api_token | length > 0
fail_msg: |
Linode API token not found.
For AWX: Attach a Linode API Token credential to your job template
For local: Set LINODE_API_TOKEN environment variable or pass linode_api_token variable
quiet: true
- name: Ensure output directory exists pre_tasks:
ansible.builtin.file: - name: Check for Linode API token (will be injected by AWX credential)
path: "{{ linode_inventory_output_dir }}" ansible.builtin.fail:
state: directory msg: "Linode API Token credential must be attached to this job template in AWX"
mode: '0755' when: linode_api_token is undefined or linode_api_token == ""
delegate_to: localhost
- name: Copy Linode inventory script - name: Display configuration
ansible.builtin.copy:
src: linode_inventory.py
dest: "{{ linode_inventory_output_dir }}/linode_inventory.py"
mode: '0755'
delegate_to: localhost
- name: Execute Linode inventory script
ansible.builtin.command:
cmd: python3 {{ linode_inventory_output_dir }}/linode_inventory.py --list
environment:
LINODE_API_TOKEN: "{{ linode_api_token }}"
register: linode_inventory_result
delegate_to: localhost
changed_when: true
- name: Show script execution details
ansible.builtin.debug: ansible.builtin.debug:
msg: | msg: |
Script execution results: Linode Inventory Configuration:
Return code: {{ linode_inventory_result.rc }} Output directory: {{ linode_inventory_output_dir }}
Stdout length: {{ linode_inventory_result.stdout | length }} Output format: {{ inventory_format }}
Stderr length: {{ linode_inventory_result.stderr | length }} AWX integration: {{ awx_integration }}
Include only running: {{ include_only_running }}
- name: Show stderr if present roles:
ansible.builtin.debug: - role: linode_inventory
msg: "Script stderr: {{ linode_inventory_result.stderr }}" vars:
when: linode_inventory_result.stderr | length > 0 linode_api_token: "{{ linode_api_token }}"
- name: Show stdout if present post_tasks:
ansible.builtin.debug: - name: Display next steps
msg: "Script stdout: {{ linode_inventory_result.stdout }}"
when: linode_inventory_result.stdout | length > 0
- name: Test API token directly
ansible.builtin.uri:
url: "https://api.linode.com/v4/linode/instances"
method: GET
headers:
Authorization: "Bearer {{ linode_api_token }}"
Content-Type: "application/json"
return_content: yes
status_code: [200, 401, 403]
register: direct_api_test
delegate_to: localhost
- name: Display direct API test results
ansible.builtin.debug: ansible.builtin.debug:
msg: | msg: |
Direct API test results: Inventory update complete!
Status: {{ direct_api_test.status }}
Response: {{ direct_api_test.json | default('No JSON response') }}
- name: Parse inventory JSON (only if stdout exists) Next steps for AWX integration:
1. Copy the inventory script to your SCM repository
2. Create a custom inventory source in AWX
3. Point it to the linode_inventory.py script
4. Set up the Linode API credential
Files created:
- JSON inventory: {{ linode_inventory_output_dir }}/{{ linode_inventory_output_file }}
{% if inventory_format == "ini" %}
- INI inventory: {{ linode_inventory_output_dir }}/linode_static_inventory.ini
{% endif %}
# Optional: Run against discovered Linode hosts
- name: Debug and use discovered Linode hosts
hosts: localhost
gather_facts: false
tasks:
- name: Check if inventory file exists
ansible.builtin.stat:
path: "{{ linode_inventory_output_dir | default('/tmp/linode_inventory') }}/{{ linode_inventory_output_file | default('linode_inventory.json') }}"
register: inventory_file_stat
- name: Display inventory file status
ansible.builtin.debug:
msg: |
Inventory file path: {{ linode_inventory_output_dir | default('/tmp/linode_inventory') }}/{{ linode_inventory_output_file | default('linode_inventory.json') }}
File exists: {{ inventory_file_stat.stat.exists }}
File size: {{ inventory_file_stat.stat.size | default(0) }} bytes
- name: Load and display inventory contents
ansible.builtin.slurp:
src: "{{ linode_inventory_output_dir | default('/tmp/linode_inventory') }}/{{ linode_inventory_output_file | default('linode_inventory.json') }}"
register: inventory_content
when: inventory_file_stat.stat.exists
- name: Parse inventory JSON
ansible.builtin.set_fact: ansible.builtin.set_fact:
linode_inventory_data: "{{ linode_inventory_result.stdout | from_json }}" dynamic_inventory: "{{ inventory_content.content | b64decode | from_json }}"
when: inventory_file_stat.stat.exists
- name: Display parsed inventory summary
ansible.builtin.debug:
msg: |
Inventory loaded successfully!
Total hostvars: {{ dynamic_inventory._meta.hostvars | length }}
Groups: {{ dynamic_inventory.keys() | reject('equalto', '_meta') | list }}
Hosts in hostvars: {{ dynamic_inventory._meta.hostvars.keys() | list }}
when: dynamic_inventory is defined
- name: Add discovered hosts to in-memory inventory
ansible.builtin.add_host:
name: "{{ item.key }}"
groups: discovered_linodes
ansible_host: "{{ item.value.ansible_host }}"
linode_id: "{{ item.value.linode_id }}"
linode_region: "{{ item.value.linode_region }}"
linode_type: "{{ item.value.linode_type }}"
linode_status: "{{ item.value.linode_status }}"
linode_tags: "{{ item.value.linode_tags }}"
is_debian: "{{ item.value.is_debian }}"
is_ubuntu: "{{ item.value.is_ubuntu }}"
is_k3s: "{{ item.value.is_k3s }}"
is_control_plane: "{{ item.value.is_control_plane }}"
is_worker_node: "{{ item.value.is_worker_node }}"
tag_string: "{{ item.value.tag_string }}"
loop: "{{ dynamic_inventory._meta.hostvars | dict2items }}"
when: when:
- linode_inventory_result.stdout | length > 0 - dynamic_inventory is defined
- linode_inventory_result.rc == 0 - item.value.linode_status == "running"
- name: Set empty inventory if script failed - name: Display added hosts with tag information
ansible.builtin.set_fact:
linode_inventory_data:
_meta:
hostvars: {}
all:
children: ['ungrouped']
ungrouped:
hosts: []
when: linode_inventory_data is not defined
- name: Save inventory to file
ansible.builtin.copy:
content: "{{ linode_inventory_data | to_nice_json }}"
dest: "{{ temp_inventory_path }}"
mode: '0644'
delegate_to: localhost
- name: Display inventory summary
ansible.builtin.debug: ansible.builtin.debug:
msg: | msg: |
Linode Dynamic Inventory Summary: Added {{ groups['discovered_linodes'] | default([]) | length }} running Linode hosts to inventory
Total hosts discovered: {{ linode_inventory_data._meta.hostvars | length }}
Groups created: {{ linode_inventory_data.keys() | reject('equalto', '_meta') | list | length }}
Inventory saved to: {{ temp_inventory_path }}
API Token status: {{ 'Set (' + (linode_api_token[:8] + '...' if linode_api_token | length > 8 else linode_api_token) + ')' if linode_api_token is defined else 'NOT SET' }}
- name: Show raw script output for debugging Host details:
{% for host in groups['discovered_linodes'] | default([]) %}
- {{ host }} ({{ hostvars[host]['ansible_host'] }})
Tags: {{ hostvars[host]['linode_tags'] | join(', ') }}
K3s: {{ hostvars[host]['is_k3s'] }}
Control Plane: {{ hostvars[host]['is_control_plane'] }}
Worker: {{ hostvars[host]['is_worker_node'] }}
{% endfor %}
- name: Test connection to discovered Linode hosts
hosts: discovered_linodes
gather_facts: false
vars:
ansible_user: phlux
ansible_ssh_common_args: '-o StrictHostKeyChecking=no -o ConnectTimeout=10'
tasks:
- name: Test connectivity
ansible.builtin.ping:
register: ping_result
ignore_errors: true
- name: Display connectivity status with tag info
ansible.builtin.debug: ansible.builtin.debug:
var: linode_inventory_result.stdout msg: |
when: linode_inventory_result.stdout | length > 0 {{ inventory_hostname }} ({{ ansible_host }}): {{ 'REACHABLE' if ping_result is succeeded else 'UNREACHABLE' }}
Tags: {{ linode_tags | join(', ') }}
Role: {{ 'Control Plane' if is_control_plane else 'Worker Node' if is_worker_node else 'Other' }}
- name: Show discovered hosts # Example: Run tasks only on k3s control plane nodes
- name: Example - Control Plane specific tasks
hosts: discovered_linodes
gather_facts: false
vars:
ansible_user: phlux
tasks:
- name: Control plane specific task
ansible.builtin.debug: ansible.builtin.debug:
msg: "Host: {{ item.key }} ({{ item.value.ansible_host }}) - Region: {{ item.value.linode_region }} - Status: {{ item.value.linode_status }}" msg: "This would run control plane specific commands on {{ inventory_hostname }}"
loop: "{{ linode_inventory_data._meta.hostvars | dict2items }}" when: is_control_plane | bool
loop_control:
label: "{{ item.key }}"
when: linode_inventory_data._meta.hostvars | length > 0
- name: Create static inventory file (optional) # Example: Run tasks only on k3s worker nodes
ansible.builtin.template: - name: Example - Worker Node specific tasks
src: inventory.ini.j2 hosts: discovered_linodes
dest: "{{ linode_inventory_output_dir }}/linode_static_inventory.ini" gather_facts: false
mode: '0644' vars:
when: inventory_format == "ini" ansible_user: phlux
delegate_to: localhost tasks:
- name: Worker node specific task
ansible.builtin.debug:
msg: "This would run worker node specific commands on {{ inventory_hostname }}"
when: is_worker_node | bool
- name: Clean up temporary script # Example: Run tasks on all k3s nodes (control plane + workers)
ansible.builtin.file: - name: Example - All K3s nodes
path: "{{ linode_inventory_output_dir }}/linode_inventory.py" hosts: discovered_linodes
state: absent gather_facts: false
delegate_to: localhost vars:
when: cleanup_temp_files | default(true) ansible_user: phlux
tasks:
- name: K3s cluster task
ansible.builtin.debug:
msg: "This would run on all k3s nodes: {{ inventory_hostname }}"
when: is_k3s | bool

View File

@@ -18,5 +18,5 @@
{% endfor %} {% endfor %}
[all:vars] [all:vars]
ansible_user=root ansible_user=phlux
ansible_ssh_common_args='-o StrictHostKeyChecking=no' ansible_ssh_common_args='-o StrictHostKeyChecking=no'