如何用Chef检测AWS EC2实例类型?ENA实例脚本及Ohai属性咨询
Hey there! Let's tackle your two questions about detecting EC2 instance types with Chef and Ohai, step by step:
Chef relies on Ohai to automatically gather system and cloud metadata from your EC2 instances. The most reliable way to get the instance type is using the built-in EC2 attributes Ohai pulls directly from AWS's Instance Metadata Service (IMDS).
In your Chef recipes, you can access the instance type directly with this attribute:node['ec2']['instance_type']
Here's a practical example of using this to run your script only on c5.2xlarge instances:
# Execute custom script specifically on c5.2xlarge instances execute 'run-targeted-script' do command '/path/to/your/script.sh' action :run only_if { node['ec2']['instance_type'] == 'c5.2xlarge' } end
If you want to map the output of cat /sys/class/dmi/id/product_name to an Ohai attribute, you can use the DMI metadata Ohai collects. The exact attribute matching that shell command is:node['dmi']['system']['product_name']
You can confirm this by running ohai dmi | grep product_name on your instance—this will return the same value as your shell command.
A quick best practice note: While the DMI attribute works, node['ec2']['instance_type'] is more reliable long-term. It pulls directly from AWS's metadata service, so it won't vary across different OSes or AMI configurations, whereas the DMI value might have minor inconsistencies depending on the AMI you're using.
If you ever want to explore all attributes Ohai collects, just run ohai on your instance to see the full dataset, or target specific plugins like ohai ec2 or ohai dmi to narrow down results.
内容的提问来源于stack exchange,提问作者TyMac

