如何使用CloudFormation自动化根设备卷的标记

时间:2015-11-10 03:50:37

标签: amazon-web-services amazon-cloudformation

我无法使用tagroot device volume EC2 CloudFormation附加到block device mapping,因为tags未传播到亚马逊从EBS创建的block device mappings卷。 root device volume tagging可以Cloudformation以任何方式使用{{3}} 自动吗?感谢。

1 个答案:

答案 0 :(得分:5)

用户数据

这可以使用UserData - 如果您正在运行带有cloudinit和awscli installed的Linux主机,则可以在UserData脚本中运行以下内容来标记所有卷与实例关联

"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"

确保在启动EC2实例时,它具有实例IAM策略,使其能够创建标记并描述卷

"PolicyDocument": {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "ec2:CreateTags",
                "ec2:DescribeVolumes"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

CloudWatch Events

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

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