0

I want to filter strings in a list based on a regular expression. I tried defining as variable ${TagValue} but it gives null value or an empty list:

Bascially i want to list down those instances that have Environment tag is equal to the "Tag Value":

Here's my code:

TagValue = ['DEV', 'DEVDR', 'QA','TEST', 'SND', 'STG', 'sit', 'sandbox', 'Development', 'NonProd', 'NON-PROD']
instance_list = []
Instances = ec2_resource.instances.all()
for each in Instances:
    instance_list.append(each.id) # count total # of instances including all env tags 
        
for i in instance_list:
    ins_res = ec2_resource.Instance(i)
    ins_tag = ins_res.tags
    ins_state = ins_res.state
    if ins_state['Name']=='running':
        for item in ins_tag:
            if item['Key'] == 'Environment':
                val = item['Value']
                pattern = re.compile(r'\b${tag_value}\w*', re.IGNORECASE)
                print(re.findall(pattern,val)) 

Output is:

[]
[]
[]
.....
5
  • A couple things about this I don't understand. You define TagValue, but then don't use it anywhere. The {tag_value} in r'\b${tag_value}\w*' isn't getting replaced with something meaningful right? It's just the plain string "{tag_value}". Commented Jan 26, 2024 at 20:36
  • $ in the regexp matches the end of the string. It doesn't make sense to have {tag_value} after that. Commented Jan 26, 2024 at 20:52
  • 1
    Are you confusing Python f-strings with JavaScript template literals? In Python you don't put $ before {expression}. Commented Jan 26, 2024 at 20:52
  • Are you trying to find any of the words in TagValue? See stackoverflow.com/questions/33406313/… Commented Jan 26, 2024 at 20:57
  • Note that you can supply filters on the describe_instances call though it doesn't support regular expressions. Commented Jan 26, 2024 at 21:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.