AWS-IAM-创建角色(图文教程)

  1. 概要
  2. 演示账号
  3. 添加策略 - 账号1
  4. 创建角色 - 账号1
  5. 添加策略 - 账号2
    1. Developers
    2. Testers
    3. 检验1 - 切换角色
    4. 检验2 - 切换角色
    5. 详解
  6. k8s本地初始化配置 - 账号2
    1. 安装工具
    2. 初始化aws账号
    3. 初始化EKS集群配置
      1. 非集群创建者
      2. 集群创建者

概要

img

  1. 账号一
    1. 创建策略
    2. 创建角色(将策略、账号二添加进去,以此关联账号)
  2. 账号二
    1. 创建群,并关联角色
    2. 创建该群下的用户
    3. 该用户使用角色

演示账号

这两有两个账号,分别是:

  • 账号一:684454806125 kyakya
  • 账号二:417942197288kyakya_02

image-20200626204931372

image-20200626204508652

添加策略 - 账号1

根据官方教程,我们在kyakya账号中设置了如下策略policy

image-20200626205213403

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 策略名:read-write-app-bucket
# JSON内容:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:ListAllMyBuckets",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListBucket",
        "s3:GetBucketLocation"
       ],
      "Resource": "arn:aws:s3:::productionapp"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"
      ],
      "Resource": "arn:aws:s3:::productionapp/*"
    }
  ]
}

创建角色 - 账号1

创建角色使用的ID是kyakya_02的ID,如下所示:

image-20200626205511971

使用刚刚创建的策略read-write-app-bucket

image-20200626205629382

角色名为UpdateApp

image-20200626205733830

创建结果:

image-20200626205840500

摘要Summary

image-20200626205917132

这里的

  • Role ARNAmazon Resource Name信息(arn:aws:iam::684454806125:role/UpdateApp)等等JSON文件需要用到。
  • Give this link to users who can switch roles in the console :账号2的用户设置完一切后,可用该链接就可以切换角色

添加策略 - 账号2

kyakya_02账号中有两个群Group,如图:

image-20200626213753494

分别是:

  • Developers
  • Testers

Developers

为(Group)Developers添加策略:

image-20200626214200942

点击自定义策略Custom Policy,如图:

image-20200626215255118

添加的内容如下:

image-20200626214342777

1
2
3
4
5
6
7
8
9
10
# 名称 UpdateApp 
# 内容
{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "sts:AssumeRole",
    "Resource": "arn:aws:iam::684454806125:role/UpdateApp" #对应ARN
  }
}

Testers

1
2
3
4
5
6
7
8
9
10
# 名称 UpdateApp 
# 内容
{
  "Version": "2012-10-17", 
  "Statement": {
    "Effect": "Deny",
    "Action": "sts:AssumeRole",
    "Resource": "arn:aws:iam::684454806125:role/UpdateApp" #对应ARN
  }
}

检验1 - 切换角色

image-20200626215519581

添加完毕后,我们发现内联策略Inline Policy被打上了,说明整个操作的目的是为内联策略

这时,我们试着添加用户User到组Group中:

image-20200627005140981

创建后,我们用这个用户User登陆一下:

image-20200627005304978

这时,我们是普通用户

再通过账号1kyakya中有这个链接:

image-20200627004958948

我们成功切换了角色:

image-20200627005410577

在第一次切换完毕后,我们的设置处,就会有记录了,下次就不用该链接了:

image-20200627005519687

检验2 - 切换角色

刚刚我们还创建了一个TestersGroup,该群设置EffectDeny,也就是不允许进行切换角色。

我们创建一个角色看看:

image-20200627011751048

通过这个角色登陆后,进行切换时,出现该警告⚠:

image-20200627011831187

证明了该用户真的没权限切换。

详解

TestersDevelopers的章节我们出现了该配置:

1
2
3
4
5
6
7
8
{
  "Version": "2012-10-17", 
  "Statement": {
    "Effect": "Deny",
    "Action": "sts:AssumeRole",
    "Resource": "arn:aws:iam::684454806125:role/UpdateApp" #对应ARN
  }
}

详解:

  • Effect:默认值为Deny,如果我们想要使用该资源,必须设置成Allow。

  • "Action": "sts:AssumeRole": assume role可以理解成开始成为某个角色[merriam-webster]

  • Resource:值为上文中的Role ARNAmazon Resource Name的内容。

k8s本地初始化配置 - 账号2

账号2该如何初始化K8s本地配置呢?

首先我们要确认一下使用到的信息:

用户名:JeanDev arn: arn:aws:iam::056844949861:user/JeanDev

role的arn:arn:aws:iam::056844949861:role/k8sDev 该role包含管理员权限

地区: ap-northeast-1 (东京)

示例地址

安装工具

1
2
3
4
5
6
# 安装centos7虚拟机,并登陆
vagrant init centos/7
vagrant up
vagrant ssh
# centos7
sudo yum update -y

安装kubectl

1
2
3
4
sudo curl --silent --location -o /usr/local/bin/kubectl \
  https://amazon-eks.s3.us-west-2.amazonaws.com/1.17.7/2020-07-08/bin/linux/amd64/kubectl

sudo chmod +x /usr/local/bin/kubectl

安装aws cli

1
2
3
4
5
6
7
sudo yum install -y unzip
# 安装aws cli
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
# 确认版本
aws --version

初始化aws账号

在AWS IAM的用户界面上,找到Create access key创建访问密钥

image-20200804212514836

运行下面的命令时,输入页面上的Access key IDSecret access key[aws]

1
2
3
4
5
6
7
8
9
# 此时我们并没有 ~/.aws和~/.kube 文件夹
$ ls -a
..
# 配置aws
$ aws configure
AWS Access Key ID [None]: AKIAQ2PBZDFSVGOM6KJH  # 输入Access key ID
AWS Secret Access Key [None]: f3UBsqDtYHZly+XQpklUmnQ6HsSKtPNYvU6kx2JV # 输入Secret access key
Default region name [None]: ap-northeast-1 # 输入地区
Default output format [None]: json

获得当前aws调用者的身份识别,我们对其进行确认:[get-caller-identity]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$  aws sts get-caller-identity
{
    "UserId": "AIDAQ2PBZDFSUB6XGNISQ",
    "Account": "056844949861",
    "Arn": "arn:aws:iam::056844949861:user/JeanDev"
}

# 成功生成aws的配置文件,并且内容是正确
$ ls .aws/
config  credentials
]$ cat .aws/credentials 
[default]
aws_access_key_id = AKIAQ2PBZDFSVGOM6KJH
aws_secret_access_key = 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
$ cat .aws/config 
[default]
region = ap-northeast-1
output = json

初始化EKS集群配置

首先,我们知道一个用户可能会同时操作多个地区(如同时操作东京地区和北美地区),而每个地区可能有若干个集群,而在执行每个地区时可能是以某个身份进行操作。

非集群创建者

通过该命令可以初始化~/.kube/config文件:

1
2
3
4
5
$  clustername=eksworkshop-eksctl
$  region=ap-northeast-1
$  roleArn=arn:aws:iam::056844949861:role/k8sDev #
$  aws eks update-kubeconfig  --name ${clustername}  --region ${region} --role-arn ${roleArn}
An error occurred (AccessDeniedException) when calling the DescribeCluster operation: User: arn:aws:iam::056844949861:user/JeanDev is not authorized to perform: eks:DescribeCluster on resource: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl

此时我们发现我们没权限去DescribeCluster,解决方案有以下:

  1. 直接给JeanDev添加权限。但是该行为不符合工作。

  2. 通过给k8sDev角色添加权限。但是我们此时的Role已经拥有管理员权限,使用了-role-arn {roleArn}参数也不能直接调用该角色的权限,原因可能是使用到DescribeCluster的代码比「初始化配置文件的代码并切换角色」该行为更早。

于是,我们需要手动去切换角色,切换后再执行初始化~/.kube/config命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 本例中--role-session-name的值为任意值即可
$ aws sts assume-role \
--role-arn arn:aws:iam::056844949861:role/k8sDev \
--role-session-name test-eks-role
{
    "Credentials": {
        "AccessKeyId": "ASIAQ2PBZDFSUGKRDRWV",
        "SecretAccessKey": "mMXb2op+gBP0HH99fMcukX6TrEAhoFHW+L9r2A6N",
        "SessionToken": "IQoJb3JpZ2luX2VjEPj//////////wEaDmFwLW5vcnRoZWFzdC0xIkcwRQIgNJzT0ksUbCpAvwSvf1R05BNlssyxQhrG1Pug7cTmioUCIQCefRSZ1aSFnSOb/jnW+FRzYR9ibM7afuooFiD13YrM3iqjAgjC//////////8BEAAaDDA1Njg0NDk0OTg2MSIMUDmCYDCO8dqki2hjKvcB8FVHYh3yzhJyN4STYCcdeZsRhnpWpm1nvORqGa0aHt3ZMNAjgF49SY7NFCEzO1HKY1NbAoTzJQ6hf0obk+q6wWMumwP2+AwWCkMqTYwXxW5tR6yVHZAmyY3Qmy387AkPyPXg83O75GSA2SF3WLMw5beq9uIjaaIjNiSH7ME5ka6lC3c2i8PgLrqJCsooV6biw9+AhFEv5tpAf6Y85f1GWopUSbmndX5183c3xlvxLORsqsE7TaKy7mIHciwiEjEaDGAD0KgIDhbLusJGgk74AYg+OCV8Gn2NTsaL+yLfl5hEAROZLGlRuwX801HhBCevZehSUuLXrTDjuav5BTqdAQfG99SoGBclCkElJliw6FDwItYiCa/DiO2+8MS984p9/JpFrk0jpqRp53BK1+Y+bGYudVl/lzSvKT/BuXFb1q+QmSXSqn63ZpR6VKcmh+k5H2ZNb31SeZ3vs3Py/AQ52RkSkMdRQGiR2N3RESz1apQhB4QY9P6QpFP7/VWAnefj5gcg6GLcYDR9Qrvflv2SLrQ7hEWMj99KgJCJpJ0=",
        "Expiration": "2020-08-05T17:22:59+00:00"
    },
    "AssumedRoleUser": {
        "AssumedRoleId": "AROAQ2PBZDFSUEPY7UGLB:test-eks-role",
        "Arn": "arn:aws:sts::056844949861:assumed-role/k8sDev/test-eks-role"
    }
}

$ export AWS_ACCESS_KEY_ID=ASIAQ2PBZDFSUGKRDRWV
$ export AWS_SECRET_ACCESS_KEY=mMXb2op+gBP0HH99fMcukX6TrEAhoFHW+L9r2A6N
$ export AWS_SESSION_TOKEN=IQoJb3JpZ2luX2VjEPj//////////wEaDmFwLW5vcnRoZWFzdC0xIkcwRQIgNJzT0ksUbCpAvwSvf1R05BNlssyxQhrG1Pug7cTmioUCIQCefRSZ1aSFnSOb/jnW+FRzYR9ibM7afuooFiD13YrM3iqjAgjC//////////8BEAAaDDA1Njg0NDk0OTg2MSIMUDmCYDCO8dqki2hjKvcB8FVHYh3yzhJyN4STYCcdeZsRhnpWpm1nvORqGa0aHt3ZMNAjgF49SY7NFCEzO1HKY1NbAoTzJQ6hf0obk+q6wWMumwP2+AwWCkMqTYwXxW5tR6yVHZAmyY3Qmy387AkPyPXg83O75GSA2SF3WLMw5beq9uIjaaIjNiSH7ME5ka6lC3c2i8PgLrqJCsooV6biw9+AhFEv5tpAf6Y85f1GWopUSbmndX5183c3xlvxLORsqsE7TaKy7mIHciwiEjEaDGAD0KgIDhbLusJGgk74AYg+OCV8Gn2NTsaL+yLfl5hEAROZLGlRuwX801HhBCevZehSUuLXrTDjuav5BTqdAQfG99SoGBclCkElJliw6FDwItYiCa/DiO2+8MS984p9/JpFrk0jpqRp53BK1+Y+bGYudVl/lzSvKT/BuXFb1q+QmSXSqn63ZpR6VKcmh+k5H2ZNb31SeZ3vs3Py/AQ52RkSkMdRQGiR2N3RESz1apQhB4QY9P6QpFP7/VWAnefj5gcg6GLcYDR9Qrvflv2SLrQ7hEWMj99KgJCJpJ0=

export了变量后,我们之后执行的语句中的AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SESSION_TOKEN均已变了。

身份识别已经变成assumed-role/k8sDev/test-eks-role(切换角色成功):

1
2
3
4
5
6
$ aws sts get-caller-identity
{
    "UserId": "AROAQ2PBZDFSUEPY7UGLB:test-eks-role",
    "Account": "056844949861",
    "Arn": "arn:aws:sts::056844949861:assumed-role/k8sDev/test-eks-role"
}

此时我们已经可以初始化~/.kube/config配置文件了:

1
2
3
4
5
6
7
$ clustername=eksworkshop-eksctl
$ region=ap-northeast-1
$ aws eks update-kubeconfig  --name ${clustername}  --region ${region}
Added new context arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl to /home/vagrant/.kube/config
# 可以访问到集群了
$ kubectl get pods --namespace=development
No resources found in development namespace.

请注意,我们此时执行的是:

1
aws eks update-kubeconfig  --name ${clustername}  --region ${region}

而不是:

1
aws eks update-kubeconfig  --name ${clustername}  --region ${region} --role-arn ${roleArn}

此时我们再重新登录虚拟机

1
2
3
4
5
6
7
8
9
10
11
$ exit
$ vagrant ssh
# 我们没有权限登录集群了
$ kubectl get pods --namespace=development
error: You must be logged in to the server (Unauthorized)
$ aws sts get-caller-identity
{
    "UserId": "AIDAQ2PBZDFSUB6XGNISQ",
    "Account": "056844949861",
    "Arn": "arn:aws:iam::056844949861:user/JeanDev"
}

因为我们退出了shell会话,所以刚刚的手动切换角色已经失效了。

为了一直都处于切换角色的状态下,我们需要 --role-arn {roleArn}参数,在这之前,我们先看看执行前的~/.kube/config 的样子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$ cat ~/.kube/config 
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: # 证书数据
    server: https://2C1A77626A2087EBA1D1123EA9398DAF.gr7.ap-northeast-1.eks.amazonaws.com
  name: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
contexts:
- context:
    cluster: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
    user: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
  name: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
current-context: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
kind: Config
preferences: {}
users:
- name: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1alpha1
      args:
      - --region
      - ap-northeast-1
      - eks
      - get-token
      - --cluster-name
      - eksworkshop-eksctl
      command: aws

增加多一个配置:

1
2
3
4
5
6
7
8
9
10
# 重新手动切换角色
$ export AWS_ACCESS_KEY_ID=ASIAQ2PBZDFSUGKRDRWV
$ export AWS_SECRET_ACCESS_KEY=mMXb2op+gBP0HH99fMcukX6TrEAhoFHW+L9r2A6N
$ export AWS_SESSION_TOKEN=IQoJb3JpZ2luX2VjEPj//////////wEaDmFwLW5vcnRoZWFzdC0xIkcwRQIgNJzT0ksUbCpAvwSvf1R05BNlssyxQhrG1Pug7cTmioUCIQCefRSZ1aSFnSOb/jnW+FRzYR9ibM7afuooFiD13YrM3iqjAgjC//////////8BEAAaDDA1Njg0NDk0OTg2MSIMUDmCYDCO8dqki2hjKvcB8FVHYh3yzhJyN4STYCcdeZsRhnpWpm1nvORqGa0aHt3ZMNAjgF49SY7NFCEzO1HKY1NbAoTzJQ6hf0obk+q6wWMumwP2+AwWCkMqTYwXxW5tR6yVHZAmyY3Qmy387AkPyPXg83O75GSA2SF3WLMw5beq9uIjaaIjNiSH7ME5ka6lC3c2i8PgLrqJCsooV6biw9+AhFEv5tpAf6Y85f1GWopUSbmndX5183c3xlvxLORsqsE7TaKy7mIHciwiEjEaDGAD0KgIDhbLusJGgk74AYg+OCV8Gn2NTsaL+yLfl5hEAROZLGlRuwX801HhBCevZehSUuLXrTDjuav5BTqdAQfG99SoGBclCkElJliw6FDwItYiCa/DiO2+8MS984p9/JpFrk0jpqRp53BK1+Y+bGYudVl/lzSvKT/BuXFb1q+QmSXSqn63ZpR6VKcmh+k5H2ZNb31SeZ3vs3Py/AQ52RkSkMdRQGiR2N3RESz1apQhB4QY9P6QpFP7/VWAnefj5gcg6GLcYDR9Qrvflv2SLrQ7hEWMj99KgJCJpJ0=
# 切换后再更新配置
$ clustername=eksworkshop-eksctl
$ region=ap-northeast-1
$ roleArn=arn:aws:iam::056844949861:role/k8sDev
$ aws eks update-kubeconfig  --name ${clustername}  --region ${region} --role-arn ${roleArn}
Updated context arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl in /home/vagrant/.kube/config

我们再回头看看~/.kube/config 配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$  cat ~/.kube/config 
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: # 证书数据
    server: https://2C1A77626A2087EBA1D1123EA9398DAF.gr7.ap-northeast-1.eks.amazonaws.com
  name: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
contexts:
- context:
    cluster: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
    user: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
  name: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
current-context: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
kind: Config
preferences: {}
users:
- name: arn:aws:eks:ap-northeast-1:056844949861:cluster/eksworkshop-eksctl
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1alpha1
      args:
      - --region
      - ap-northeast-1
      - eks
      - get-token
      - --cluster-name
      - eksworkshop-eksctl
      - --role
      - arn:aws:iam::056844949861:role/k8sDev
      command: aws

发现多了两行:

1
2
      - --role
      - arn:aws:iam::056844949861:role/k8sDev

再退出会话看看永久化了没:

1
2
3
4
5
$ exit
$ vagrant ssh
# 永久化成功
$ kubectl get pods --namespace=development
No resources found in development namespace.

参考文档:

集群创建者

集群创建者在创建完集群后(在创建期间已经指定了地区、集群名),就可以直接使用。[aws] 值得一提的是,这里并没有需要指定身份,是因为在AWS EKS已经自动授予了权限(system:masters)。[aws]