Created
November 11, 2023 02:17
-
-
Save ImIOImI/f50e96e0c3c78ddceb37c71a4f6c9898 to your computer and use it in GitHub Desktop.
Ingest Terraform apply output and extract all the resources that need to be imported and write terraform import statements.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Read terraform-errors.txt and filter errors to generate terraform-import.sh | |
input_file = 'terraform-errors.txt' | |
output_file = 'terraform-import.sh' | |
try: | |
# Open the input file in read mode | |
with open(input_file, 'r') as f_in: | |
# Read lines from the input file | |
lines = f_in.readlines() | |
# Open the output file in write mode | |
with open(output_file, 'w') as f_out: | |
# Write the header to the output file | |
f_out.write('#!/bin/bash\n\n') | |
# Process each line from the input file and filter errors | |
i = 0 | |
while i < len(lines): | |
line = lines[i].strip() | |
# Check if the line contains the error pattern | |
if line.startswith('│ Error: A resource with the ID') and "already exists - to be managed via Terraform this resource needs to be imported into the State." in line: | |
# Save the first line to memory | |
first_line = f'# {line}\n' | |
# Ensure we don't go beyond the end of the list | |
i += 2 # Skip the blank line | |
if i < len(lines): | |
# Get the resource name from the second line and remove the trailing comma | |
resource_line = lines[i].strip().split()[2].rstrip(',') | |
# Generate the import command | |
import_command = f'terraform import \'{resource_line}\' ' | |
# Print the import command | |
f_out.write(import_command) | |
# Extract only the content within the quotes from the first line | |
first_line_content = first_line.split('"')[1] | |
# Print the modified first line with single quotes | |
f_out.write(f'\'{first_line_content}\'\n') | |
i += 1 | |
print(f'Successfully generated {output_file}') | |
except FileNotFoundError: | |
print(f'Error: File {input_file} not found.') | |
except Exception as e: | |
print(f'An error occurred: {str(e)}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment