Skip to content

Instantly share code, notes, and snippets.

@MarWeUMR
Last active March 10, 2024 13:41
Show Gist options
  • Save MarWeUMR/e8d844b3fc3ead186981964f810db357 to your computer and use it in GitHub Desktop.
Save MarWeUMR/e8d844b3fc3ead186981964f810db357 to your computer and use it in GitHub Desktop.

How to use the ansible debugger

[192.0.2.10] TASK: install package (debug)> p task
TASK: install package
[192.0.2.10] TASK: install package (debug)> p task.args
{u'name': u'{{ pkg_name }}'}
[192.0.2.10] TASK: install package (debug)> p task_vars
{u'ansible_all_ipv4_addresses': [u'192.0.2.10'],
 u'ansible_architecture': u'x86_64',
 ...
}
[192.0.2.10] TASK: install package (debug)> p task_vars['pkg_name']
u'bash'
[192.0.2.10] TASK: install package (debug)> p host
192.0.2.10
[192.0.2.10] TASK: install package (debug)> p result._result
{'_ansible_no_log': False,
 'changed': False,
 u'failed': True,
 ...
 u'msg': u"No package matching 'not_exist' is available"}
 
 [192.0.2.10] TASK: install package (debug)> p task.args
{u'name': u'{{ pkg_name }}'}
[192.0.2.10] TASK: install package (debug)> task.args['name'] = 'bash'
[192.0.2.10] TASK: install package (debug)> p task.args
{u'name': 'bash'}
[192.0.2.10] TASK: install package (debug)> redo

How to upload a file from local machine to servers

- name: my file upload
  copy:
    src: file_in_files_folder_of_my_role.tar.gz # placing under files folder is the relevant part here
    dest: /opt/or_somewhere_else_on_server.tar.gz
    mode: '0444' # optional
  become: yes # optional

How to create a folder

- name: create a directory
  file:
    path: /opt/my_path
    state: directory
    mode: 0755
    owner: <user>
    group: <user_group>
  become: yes # optional

How to get facts of all hosts when playing with 'serial: 1'

---
- name: Gather facts from all hosts
  hosts: all
  gather_facts: true

- name: Do something sequentially
  hosts: all
  gather_facts: false
  serial: 1

  roles:
    # in this role the facts of all hosts will be available
    # e.g. all ips, hostnames etc.
    - role: my_sequential_role # e.g. rke2 install

How to get all fqdns for jinja templating

{% for host in groups['all'] %}
  {% if hostvars[host]['ansible_fqdn'] is defined %}
    "{{ hostvars[host]['ansible_fqdn'] }}"
  {% endif %}
{% endfor %}

How to dump task_vars from the ansible debugger to a file?

Intended for the use in a debugger session that was started with strategy=debug or debugger: on_failed etc. This is great to further process the dump to json content. See ansible_debugger_json_converter.py for more on that.

Simple vars dump

This will not be proper json formatted filecontent.

with open('file.json', 'w') as f: f.write(str(task_vars)); f.close();

Quick & Dirty variant

This will process the content and remove the raw file right away.

with open('file.json', 'w') as f: f.write(str(task_vars)); f.close(); os.system('python3 ansible_debugger_json_converter.py -i file.json'); os.remove('file.json');
import json
import ast
import argparse
import os
def convert_to_json(input_file, output_file):
"""
Intended use for ansible debugger variable dumping.
Convert a Python dictionary string in a file to a JSON file.
Args:
input_file (str): Path to the file containing the Python dictionary string.
output_file (str): Path to the output JSON file.
This function reads a file containing a Python dictionary string, safely evaluates
the string to a Python dictionary, and then writes it to a JSON file.
"""
print(f"Reading from {input_file} and writing to {output_file}")
# Read the content of the file
try:
with open(input_file, 'r') as file:
file_content = file.read()
except IOError as e:
print(f"Error reading file: {e}")
return
# Strip the outer double quotes
file_content = file_content.strip('"')
# Safely evaluate the string to a Python dictionary
try:
dict_content = ast.literal_eval(file_content)
except ValueError as e:
print(f"Error in converting to dictionary: {e}")
return
# Write the dictionary back to a file in JSON format
try:
with open(output_file, 'w') as file:
json.dump(dict_content, file, indent=4)
print(f"File successfully written to {output_file}")
except IOError as e:
print(f"Error writing file: {e}")
return
def main():
"""
Main function to handle command line arguments and invoke the conversion.
This script accepts command line arguments for input and optional output file paths.
If the output file path is not provided, the script generates the output file name
by appending '_clean' to the input file name.
"""
# Create argument parser
parser = argparse.ArgumentParser(description='Convert a file from Python dictionary string to JSON.')
parser.add_argument('-i', '--input_file', required=True, help='Input file path')
parser.add_argument('-o', '--output_file', help='Output JSON file path')
# Parse arguments
args = parser.parse_args()
# Determine the output file name
if args.output_file:
output_file = args.output_file
else:
# Append '_clean' to the input file name (before the extension)
base, ext = os.path.splitext(args.input_file)
output_file = f"{base}_clean{ext}"
# Convert and save
convert_to_json(args.input_file, output_file)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment