<p>虽然实际上不是问题的答案,但是不要将AWS凭证硬编码到脚本中。使用您的AWS凭据,<strong>任何人都可以使用您的帐户。有一些机器人正在搜索github和其他git存储库,寻找硬编码的AWS凭证。</p>
<p>另外,当轮换凭证时,所有代码都将被破坏,或者您将很难更新所有凭证。</p>
<p>一些替代方案代替硬编码您的AWS凭据:</p>
<ol>
<li>配置~/.aws/credentials文件</li>
<li>使用IAM角色</li>
<li>使用STS“assumeRole”</li>
</ol>
<p>遵循此处描述的最佳实践:<a href="https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html" rel="nofollow noreferrer">Best Practices for Managing AWS Access Keys</a></p>
<p>现在,为了回答您的问题,下面是一个如何按标记筛选的示例:</p>
<pre><code>argEnv = '<any_string_you_want_to_match_as_a_value_for_a_tag>'
ec2Client = boto3.client('ec2')
response = ec2Client.describe_instances(
Filters=[
{
'Name': 'tag:Projeto',
'Values': [argEnv]
}
]
)
</code></pre>
<p>确保'Value'是一个列表而不是一个字符串。例如,如果“argEnv”是一个字符串,请确保使用“[%”封装变量。</p>
<p>然后,如果要查询Tag:Name并获取其值(例如,在控制台中为特定EC2实例设置的名称):</p>
<pre><code>for reservation in res['Reservations']:
for instance in reservation['Instances']:
for tag in instance['Tags']:
if tag['Key'] == 'Name':
consoleName = tag['Value']
print(consoleName)
</code></pre>
<p>输出将是每个资源的名称标记的值。如您所见,您必须循环遍历结果以获得结果。您可以检查响应语法<a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances" rel="nofollow noreferrer">here</a>。</p>