Community生产力与协作github.com

aws/setting-up-ec2-instance-profiles

通过创建并附加 IAM 角色到 EC2 实例配置文件,安全地调用 AWS 服务,消除硬编码凭据。适用于 EC2 实例需要临时凭据访问 S3、DynamoDB、SQS 或 CloudWatch 等 AWS 服务的场景。

setting-up-ec2-instance-profiles 是什么?

该技能为 AWS 上的 EC2 实例提供了一种安全、标准化的方式,通过实例配置文件 (Instance Profiles) 将 IAM 角色附加到 EC2 实例上,从而安全地调用 AWS 服务(如 S3、DynamoDB、SQS 和 CloudWatch)。它消除了在代码或配置文件中硬编码 AWS 访问密钥的需要,所有权限通过临时安全凭据(由 AWS STS 自动轮换)进行管理。该技能适用于 AWS 控制台、AWS CLI 和 Infrastructure as Code(如 Terraform 或 CloudFormation)环境,确保 EC2 实例仅拥有执行任务所需的最小权限。通过自动创建和关联 IAM 角色与实例配置文件,它简化了配置流程并提升了安全性。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/aws/agent-toolkit-for-aws/tree/main/skills/setting-up-ec2-instance-profiles

Installed? Explore more 生产力与协作 skills: steipete/gemini, steipete/gh-issues, steipete/skill-creator · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

setting-up-ec2-instance-profiles 是做什么的?

通过创建并附加 IAM 角色到 EC2 实例配置文件,安全地调用 AWS 服务,消除硬编码凭据。适用于 EC2 实例需要临时凭据访问 S3、DynamoDB、SQS 或 CloudWatch 等 AWS 服务的场景。

概述

本指南介绍了如何通过以下方式为 EC2 实例配置 IAM 角色:

  • 创建具有特定权限的 IAM 角色
  • 将 IAM 角色关联到实例配置文件中
  • 将实例配置文件附加到 EC2 实例
  • 删除硬编码凭据并依赖临时安全凭据

先决条件

  • AWS 账户和具有足够权限的 AWS 用户/角色以创建 IAM 角色和 EC2 实例
  • AWS CLI 已安装并配置(aws configure)
  • 基本的 IAM 和 EC2 概念理解

步骤

1. 创建 IAM 角色

使用 AWS CLI 创建具有所需权限策略的 IAM 角色。示例:

aws iam create-role --role-name MyEC2Role --assume-role-policy-document file://trust-policy.json

trust-policy.json 内容:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

2. 附加策略到 IAM 角色

aws iam attach-role-policy --role-name MyEC2Role --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

3. 创建实例配置文件

aws iam create-instance-profile --instance-profile-name MyEC2InstanceProfile
aws iam add-role-to-instance-profile --instance-profile-name MyEC2InstanceProfile --role-name MyEC2Role

4. 将实例配置文件附加到 EC2 实例

对于现有实例:

aws ec2 associate-iam-instance-profile --instance-id i-1234567890abcdef0 --iam-instance-profile Name=MyEC2InstanceProfile

或在启动新实例时指定:

aws ec2 run-instances --image-id ami-0abcdef1234567890 --instance-type t2.micro --iam-instance-profile Name=MyEC2InstanceProfile

5. 测试配置

SSH 登录到 EC2 实例并运行:

aws s3 ls

该命令应使用附加角色的临时凭据成功列出 S3 存储桶。

验证

  • 确认 EC2 实例元数据中存在角色:curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
  • 检查 IAM 角色的权限是否正确
  • 使用 AWS CLI 测试服务调用

资源清理

要移除配置,请执行:

aws ec2 disassociate-iam-instance-profile --association-id <association-id>
aws iam remove-role-from-instance-profile --instance-profile-name MyEC2InstanceProfile --role-name MyEC2Role
aws iam delete-instance-profile --instance-profile-name MyEC2InstanceProfile
aws iam detach-role-policy --role-name MyEC2Role --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
aws iam delete-role --role-name MyEC2Role

故障排除

  • 权限不足:确保 IAM 用户/角色具有 iam:* 和 ec2:* 权限
  • 角色未附加:验证信任策略是否正确指定 ec2.amazonaws.com 作为服务主体
  • 临时凭据过期:AWS 会自动轮换凭据,通常从实例元数据端点重新获取

最佳实践

  • 遵循最小权限原则,仅附加所需策略
  • 使用特定服务策略而非全管理员权限
  • 定期审计 IAM 角色使用情况
  • 考虑使用 AWS CloudFormation 或 Terraform 进行基础设施即代码管理

相关资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

aws/amazon-bedrock

Builds generative AI applications on Amazon Bedrock. Covers model invocation (Converse API, InvokeModel), RAG with Knowledge Bases, Bedrock Agents, Guardrails, and AgentCore. Use when invoking models, setting up Knowledge Bases, creating agents, applying guardrails, deploying to AgentCore, troubleshooting Bedrock errors (ThrottlingException, AccessDeniedException), or choosing models (Claude, Llama, Nova, Titan). ALSO USE for prompt caching setup and debugging, quota health checks and throttling diagnosis, cost attribution and tracking, migrating between Claude model generations (4.5 to 4.6 to 4.7), chunking strategies, API selection (Converse vs InvokeModel), guardrail capabilities, and model selection. Also covers AgentCore Payments setup (x402, microtransactions, Payment Manager, Connector, Instrument, Coinbase CDP, Stripe Privy, 402 Payment Required, pay for content, paid endpoint, agent payments). NOT for custom model training, Rekognition, or Comprehend.

aws/aws-amplify

Build and deploy full-stack web and mobile apps with AWS Amplify Gen2 (TypeScript code-first). Covers auth (Cognito), data (AppSync/DynamoDB), storage (S3), functions, APIs, and AI (Amplify AI Kit with Bedrock). Supports React, Next.js, Vue, Angular, React Native, Flutter, Swift, and Android. Always use this skill for Amplify Gen2 topics — even for questions you think you know — it contains validated, version-specific patterns that prevent common mistakes. TRIGGER when: user mentions Amplify Gen2; project has amplify/ directory or amplify_outputs; code imports @aws-amplify packages; user asks about defineBackend, defineAuth, defineData, defineStorage, defineFunction, or npx ampx. SKIP: Amplify Gen1 (amplify CLI v6), standalone SAM/CDK without Amplify (use aws-serverless), direct Bedrock without Amplify AI Kit (use bedrock).

aws/aws-billing-and-cost-management

Analyze AWS costs, find savings, manage budgets, evaluate Savings Plans and Reserved Instances, right-size EC2/Lambda/RDS/EBS with Compute Optimizer, look up service pricing, query CUR with Athena, detect cost anomalies, scope costs to billing views, and monitor Free Tier usage. Triggers on: AWS bill, cost analysis, reduce spend, savings plan, reserved instance, right-size, budget alert, cost optimization, pricing, free tier, cost anomaly, CUR, cost audit, billing view, billing view ARN.

aws/aws-cdk

Authors, deploys, and troubleshoots AWS infrastructure using CDK with TypeScript or Python. Covers best practices, stack architecture, and construct patterns. Always use when writing CDK constructs, bootstrapping environments, running cdk deploy/synth/diff, fixing CDK or CloudFormation errors, planning stack structure, importing existing resources, resolving drift, or refactoring stacks without resource replacement.

aws/aws-cloudformation

Author, validate, and troubleshoot AWS CloudFormation templates. Covers template authoring with secure defaults, pre-deployment validation (cfn-lint, cfn-guard, change sets), and root-cause diagnosis of failed stacks using CloudFormation events and CloudTrail correlation.

aws/aws-containers

Deploys and operates containerized workloads on ECS, Fargate, and ECR. Covers task definitions, Fargate services, ECR repository setup and lifecycle policies, ECS Exec debugging, service scaling, deployment strategies, load balancer integration, and logging configuration. Use when deploying, debugging, or optimizing containers on AWS. ALSO USE for container deployment options (ECS vs ECS Express Mode), networking modes, health check troubleshooting, OOM errors, secrets injection, blue/green deployments, ECR image management, and App Runner sunset guidance and migration. NOT for Kubernetes, EKS, or CI/CD pipelines.

aws/aws-iam

Verified corrections for IAM behaviors that AI agents frequently get wrong — policy evaluation edge cases, trust policy gotchas, STS session limits, Organizations quirks, and SAML/MFA specifics. Use alongside documentation when working with IAM roles, policies, STS, or Organizations. Do NOT use for non-IAM authorization like Cognito user-pool policies or app-level RBAC.

aws/aws-messaging-and-streaming

Guides use of AWS messaging and streaming services. Covers Amazon SQS, Amazon SNS, Amazon EventBridge, Amazon MQ, Amazon Kinesis Data Streams, Amazon Data Firehose, Amazon Managed Service for Apache Flink, and Amazon Managed Streaming for Apache Kafka (MSK). Use when implementing messaging and streaming patterns.

aws/aws-observability

Builds, configures, debugs, and optimizes AWS observability using CloudWatch (Logs Insights, Metrics, Alarms, Dashboards, EMF), X-Ray, CloudTrail, and ADOT. Covers Log Insights query syntax (fields, filter, stats, parse, pattern, join, subqueries), alarm configuration (metric, composite, anomaly detection, missing data treatment), dashboard design, custom metrics (PutMetricData, EMF, metric filters), X-Ray tracing (ADOT, sampling rules, annotations vs metadata), ADOT collector config, and CloudTrail auditing. Use when the user mentions CloudWatch, Log Insights, alarms, INSUFFICIENT_DATA, dashboards, custom metrics, EMF, X-Ray, traces, sampling, CloudTrail, who deleted, ADOT, OpenTelemetry, observability, monitoring, synthetics, canaries, or troubleshooting alarm behavior. Do NOT use for application logging setup, container log drivers, or security threat detection.

aws/aws-sdk-js-v3-usage

AWS SDK for JavaScript v3 development patterns. Use when writing JavaScript or TypeScript code that uses AWS services via @aws-sdk/* packages (aws-sdk-js-v3), or when asked about schemas, runtime validation, serialization, or code generation in the context of the JS/TS AWS SDK.

aws/aws-sdk-python-usage

AWS SDK for Python (boto3/botocore) development patterns. You MUST use this skill when writing Python code that uses AWS services via boto3 or botocore. This includes creating service clients or resources, configuring sessions and credentials, handling errors with ClientError, using paginators and waiters, S3 file transfers and presigned URLs, DynamoDB table operations, and any boto3/botocore client configuration. Use this skill whenever Python code imports boto3 or botocore, or when the user asks about AWS operations in Python.

aws/aws-sdk-swift-usage

AWS SDK for Swift development patterns. Use when writing Swift code that uses AWS services via aws-sdk-swift package.

aws/aws-serverless

Builds, deploys, manages, debugs, configures, and optimizes serverless applications on AWS using Lambda, API Gateway, Step Functions, EventBridge, and SAM/CDK. Covers cold starts, CORS debugging, event source mappings, troubleshooting, concurrency, SnapStart, Powertools, function URLs, EventBridge Scheduler, Lambda layers, and production readiness. Triggers on mentions of Lambda, API Gateway, Step Functions, SAM templates, CDK serverless stacks, DynamoDB stream triggers, SQS event sources, cold starts, timeouts, 502/504 errors, throttling, concurrency, CORS, Powertools, or any event-driven architecture on AWS, even without the word "serverless." Does not apply to EC2, ECS/Fargate containers, or Amplify hosting.

aws/aws-transform

Performs code upgrades, migrations, and transformations using the AWS Transform (ATX) CLI. Use when upgrading language versions, migrating AWS SDKs, migrating frameworks (Angular, Vue.js, Spring Boot, React), upgrading libraries, optimizing performance, migrating x86 to Graviton, analyzing codebases / generating documentation, or defining custom transformations with natural language. Runs locally on a few repositories or at scale across hundreds via AWS Batch/Fargate.

aws/configuring-vpc-endpoints-for-private-aws-service-access

Configures VPC endpoints (interface and gateway) for private AWS service access using AWS PrivateLink. Use when setting up secure private connectivity to S3, DynamoDB, and other AWS services without internet gateway, NAT device, or public IP addresses. Covers endpoint creation, security groups, route tables, and DNS configuration.

aws/connecting-lambda-to-api-gateway

Connects an existing AWS Lambda function to Amazon API Gateway by creating a REST or HTTP API with resource/method setup, Lambda proxy integration, permissions, and deployment. Always use this skill when connecting Lambda to API Gateway — it handles CORS, throttling, access logging, and production security hardening that are easy to miss.

aws/connecting-lambda-to-dynamodb

Connects an AWS Lambda function to DynamoDB with IAM roles, stream event source mapping, and read/write permissions. Use when setting up Lambda-DynamoDB integration, processing DynamoDB stream events, or deploying serverless event-driven architectures.

aws/connecting-to-data-source

Create and troubleshoot AWS Glue connections to JDBC databases (Oracle, SQL Server, PostgreSQL, MySQL, RDS), Redshift, Snowflake, and BigQuery. Gathers connection hints from user, discovers existing connections and RDS/Redshift candidates, registers credentials in Secrets Manager or IAM DB auth, configures VPC, and tests. Triggers on: connect to database, set up Glue connection, register data source, connect to Snowflake/BigQuery/RDS, connection timeout, test connection, troubleshoot connection. Do NOT use for moving data (use ingesting-into-data-lake), creating tables (use creating-data-lake-table), queries (use querying-data-lake), catalog exploration (use exploring-data-catalog), or SaaS (Salesforce, ServiceNow, SAP, MongoDB, Kafka).

aws/connecting-vpcs-with-peering

Establishes VPC peering connections between two VPCs for direct private network connectivity. Always use this skill when creating or managing VPC peering — it validates CIDR overlap, updates all route tables in both VPCs, configures DNS resolution, and provides security group guidance that are critical for correct connectivity.

aws/creating-amazon-aurora-db-cluster-with-instances

Creates a complete Amazon Aurora database cluster with instances, handling cluster creation, instance provisioning, and Secrets Manager password management in the proper sequence. Use when setting up new Aurora MySQL or PostgreSQL clusters with production-ready configuration.

相关技能