如何通过cloudformation设置凭据?

时间:2019-02-01 18:56:24

标签: amazon-ec2 amazon-cloudformation aws-cli

我有一个cloudformation模板,可以启动ec2实例。进入此ec2实例后,我尝试从s3存储桶中检索文件。但是,为了做到这一点,我不得不使用aws configure(访问密钥,秘密访问密钥,区域等)输入我的凭据。有没有办法在ssh进入实例时自动设置这些凭据?我当时正在考虑将凭证放在cloudformation模板中的某个地方,但这似乎有点奇怪。凭证将放在哪里?

谢谢

1 个答案:

答案 0 :(得分:0)

您需要将角色附加到实例。这是一个例子

AWSTemplateFormatVersion: '2010-09-09'
Description: Attach IAM Role to an EC2
Resources:
  Test:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType:
        Ref: InstanceType
      IamInstanceProfile:
        Ref: ListS3BucketsInstanceProfile
  ListS3BucketsInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: "/"
      Roles:
      - Ref: ListS3BucketsRole
  ListS3BucketsPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: ListS3BucketsPolicy
      PolicyDocument:
        Statement:
        - Effect: Allow
          Action:
          - s3:List*
          Resource: "*"
      Roles:
      - Ref: ListS3BucketsRole
  ListS3BucketsRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ec2.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: "/"

ListS3BucketsInstanceProfile担任角色:ListS3BucketsRole
ListS3BucketsPolicy附加到ListS3BucketsRole上,该角色可以列出所有s3对象。

通过此操作,您的EC2实例可以列出S3上的文件