首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何利用CloudFormation实现根设备卷标注的自动化

如何利用CloudFormation实现根设备卷标注的自动化
EN

Stack Overflow用户
提问于 2015-11-10 03:50:36
回答 1查看 1.9K关注 0票数 9

我无法使用标签块设备映射连接到EC2上,因为标签没有传播到从块设备映射创建的亚马逊EBS卷。根装置体积贴标可以用云层形成以任何方式自动实现吗?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-14 20:31:44

CloudFormation

这是刚在CloudFormation中通过属性进行设置的

PropagateTagsToVolumeOnCreation

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-propagatetagstovolumeoncreation

用户数据

使用UserData可以这样做--如果您正在使用cloudinit和安装awscli运行linux主机,则可以在UserData脚本中运行以下代码来标记与实例关联的所有卷

代码语言:javascript
复制
"VOLUME_IDS=$(aws ec2 describe-volumes --output text --filters Name=attachment.instance-id,Values=$(curl http://169.254.169.254/latest/meta-data/instance-id) --query 'Volumes[].VolumeId')",
"aws ec2 create-tags --resources ${VOLUME_IDS} --tags Key=my,Value=tag"
  • 检索当前实例id
  • 在描述卷中使用实例id作为筛选器。
  • 只返回卷ids的jmespath查询
  • 传递给创建带有您希望添加的标记/s的标记的卷ids

确保在启动EC2实例时,它有一个允许它创建标记和描述卷的实例IAM

代码语言:javascript
复制
"PolicyDocument": {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "ec2:CreateTags",
                "ec2:DescribeVolumes"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

## CloudWatch事件的另一种自动化方式是通过CloudWatch事件,设置事件规则侦听和EC2状态更改,然后在Lambda函数中标记卷,我在下面包含了几个CloudFormation片段

代码语言:javascript
复制
LambdaEC2CopyTagsToEBS:
  Type: AWS::IAM::Role
  Properties:
    AssumeRolePolicyDocument:
      Version: 2012-10-17
      Statement:
        - Effect: Allow
          Principal:
            Service:
              - lambda.amazonaws.com
          Action:
            - sts:AssumeRole
    Policies:
      - PolicyName: LambdaEC2CopyTagsToEBS
        PolicyDocument:
          Version: 2012-10-17
          Statement:
            - Effect: Allow
              Action:
                - ec2:DescribeInstances
                - ec2:CreateTags
              Resource: '*'

            - Effect: Allow
              Action:
                - logs:CreateLogGroup
                - logs:CreateLogStream
                - logs:PutLogEvents
              Resource: '*'

LambdaEC2CopyTagsToEBSEvent:
  Type: AWS::Events::Rule
  Properties:
    Description: Invokes CopyInstanceTagsToEBSVolumes when an Instance starts running
    EventPattern:
      source:
        - aws.ec2
      detail-type:
        - EC2 Instance State-change Notification
      detail:
        state:
          - running
    State: ENABLED
    Targets:
      - Arn: !GetAtt CopyInstanceTagsToEBSVolumes.Arn
        Id: !Ref CopyInstanceTagsToEBSVolumes

CopyInstanceTagsToEBSVolumes:
  Type: AWS::Lambda::Function
  Properties:
    Description: Copies Tags from and EC2 to all its EBS Volumes
    Code:
      ZipFile: |
        import boto3
        ec2 = boto3.client('ec2')


        def get_volume_ids(instance):
            for device in instance.get('BlockDeviceMappings', []):
                yield device.get('Ebs', {}).get('VolumeId')


        def handler(event, context):
            state, instance_id = event['detail']['state'], event['detail']['instance-id']
            if state == 'running':
                instance = ec2.describe_instances(InstanceIds=[instance_id])
                instance = instance['Reservations'][0]['Instances'][0]
                volume_ids = get_volume_ids(instance)
                tags = [tag for tag in instance['Tags'] if not tag['Key'].startswith('aws:')]
                ec2.create_tags(Resources=list(volume_ids),
                                Tags=tags
                                )

    Handler: index.handler
    Role: !GetAtt LambdaEC2CopyTagsToEBS.Arn
    Runtime: python3.6
    Timeout: 5


EventsInvokeCopyInstanceTagsToEBSVolumes:
  Type: AWS::Lambda::Permission
  Properties:
    Action: lambda:InvokeFunction
    FunctionName: !Ref CopyInstanceTagsToEBSVolumes
    Principal: events.amazonaws.com
    SourceArn: !GetAtt LambdaEC2CopyTagsToEBSEvent.Arn
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33622558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档