+86 135 410 16684Mon. - Fri. 10:00-22:00

AWS EMR 使用Instance Profile 限制 S3 访问权限

AWS EMR 使用Instance Profile 限制 S3 访问权限

AWS EMR 使用Instance Profile 限制 S3 访问权限

AWS EMR 可以指定 EC2 instance profile 来限制 EMR 节点中的程序的权限.

注意: 这里说的是 EC2 instance profile, 不是 EMR role, 这两个容易混淆. 但可以肯定的是:

  • 如果想限制在 EMR 集群中的 EC2 节点上运行的程序的 AWS 相关资源的权限, 应该使用 EC2 instance profile
EC2 instance profile

而今天遇到这样一个需求: 一个 EMR 集群需要仅仅开放对 hive 的 test 数据库的读写权限. 而 test 数据库的数据存储在 s3 上.

按照以往的经验, 直接写了一个 IAM policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws-cn:s3:::test-bucket/hive/test.db/*",
                "arn:aws-cn:s3:::test-bucket/hive/test.db"
            ]
        }
    ]
}

其中 s3://test-bucket/hive/test.db 就是 test db 在 hive 中的 location. 上线测试, aws cli 访问 s3 一切正常. 但 hive 任务执行类似

CREATE TABLE test.test_table AS SELECT * FROM test.src_table;

就直接报错, 说 s3 访问失败. 到处检查无果, 最后通过报错信息中的 s3 Request ID 看出端倪: API 请求访问的 s3 路径居然是 s3://test-bucket/hive/test.db_$folder$, 简直泪奔. 居然是 hive 在访问过程中创建了临时路径的缘故.

修改了 IAM policy file, 如下:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws-cn:s3:::test-bucket/hive/test.db/*",
                "arn:aws-cn:s3:::test-bucket/hive/test.db",
                "arn:aws-cn:s3:::test-bucket/hive/test.db_$folder$/*",
                "arn:aws-cn:s3:::test-bucket/hive/test.db_$folder$"
            ]
        }
    ]
}

执行 SQL 全部成功, 只不过今后相关的 policy file 都会变成这种乱七八糟的样子.

总结

  • 限制 EMR 集群权限是非常必要的. 但由于 EMR 不支持在同一集群中实现不同用户对 s3 的权限控制, 只有通过开启不同的 EMR 集群来实现.
  • 账户默认的 EMR_EC2_DefaultRole 权限是针对所有 s3 资源 开启了 s3:* 的权限, 非常不建议使用
  • AWS IAM 设计的非常好. 可以通过 policy 的组合实现复用.

— EOF —