

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# EKS Pod 身分關聯
<a name="pod-identity-associations"></a>

AWS EKS 已推出新的增強型機制，稱為 Pod Identity Association，供叢集管理員設定 Kubernetes 應用程式，以接收與叢集外部 AWS 服務連線所需的 IAM 許可。不過，Pod Identity Association 會利用 IRSA，讓它可直接透過 EKS API 進行設定，因此完全不需要使用 IAM API。

因此，IAM 角色不再需要參考 [OIDC 供應商](iamserviceaccounts.md#iam-how-works)，因此不會再繫結至單一叢集。這表示 IAM 角色現在可以跨多個 EKS 叢集使用，而不需要在每次建立新叢集時更新角色信任政策。這樣一來，就不需要重複角色，而且可簡化自動化 IRSA 的程序。

## 先決條件
<a name="_prerequisites"></a>

在幕後，Pod 身分關聯的實作正在工作節點上執行代理程式做為協助程式集。若要在叢集上執行先決條件代理程式，EKS 會提供稱為 EKS Pod Identity Agent 的新附加元件。因此，建立 Pod 身分關聯 （一般使用 和 `eksctl`) 需要預先安裝在叢集上的`eks-pod-identity-agent`附加元件。您可以使用與任何其他支援附加元件`eksctl`相同的方式建立此附加元件。

```
eksctl create addon --cluster my-cluster --name eks-pod-identity-agent
```

此外，如果在建立 Pod 身分關聯時使用預先存在的 IAM 角色，您必須將角色設定為信任新推出的 EKS 服務主體 (`pods.eks.amazonaws.com`)。IAM 信任政策範例如下所示：

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "pods.eks.amazonaws.com"
            },
            "Action": [
                "sts:AssumeRole",
                "sts:TagSession"
            ]
        }
    ]
}
```

如果您未將現有角色的 ARN 提供給建立命令， `eksctl`會在幕後建立一個角色，並設定上述信任政策。

## 建立 Pod 身分關聯
<a name="_creating_pod_identity_associations"></a>

對於操縱 Pod 身分關聯， `eksctl`已在 下新增欄位`iam.podIdentityAssociations`，例如

```
iam:
  podIdentityAssociations:
  - namespace: <string> #required
    serviceAccountName: <string> #required
    createServiceAccount: true #optional, default is false
    roleARN: <string> #required if none of permissionPolicyARNs, permissionPolicy and wellKnownPolicies is specified. Also, cannot be used together with any of the three other referenced fields.
    roleName: <string> #optional, generated automatically if not provided, ignored if roleARN is provided
    permissionPolicy: {} #optional
    permissionPolicyARNs: [] #optional
    wellKnownPolicies: {} #optional
    permissionsBoundaryARN: <string> #optional
    tags: {} #optional
```

如需完整範例，請參閱 [pod-identity-associations.yaml](https://github.com/eksctl-io/eksctl/blob/main/examples/39-pod-identity-association.yaml)。

**注意**  
除了`permissionPolicy`用作內嵌政策文件之外，所有其他欄位都有一個 CLI 旗標對等項。

建立 Pod 身分關聯的方法如下。在叢集建立期間，透過指定所需的 Pod 身分關聯做為組態檔案的一部分並執行：

```
eksctl create cluster -f config.yaml
```

建立叢集後，使用組態檔案，例如

```
eksctl create podidentityassociation -f config.yaml
```

OR 使用 CLI 旗標，例如

```
eksctl create podidentityassociation \
    --cluster my-cluster \
    --namespace default \
    --service-account-name s3-reader \
    --permission-policy-arns="arn:aws:iam::111122223333:policy/permission-policy-1, arn:aws:iam::111122223333:policy/permission-policy-2" \
    --well-known-policies="autoScaler,externalDNS" \
    --permissions-boundary-arn arn:aws:iam::111122223333:policy/permissions-boundary
```

**注意**  
一次只能將單一 IAM 角色與服務帳戶建立關聯。因此，嘗試為相同的服務帳戶建立第二個 Pod 身分關聯將導致錯誤。

## 擷取 Pod 身分關聯
<a name="_fetching_pod_identity_associations"></a>

若要擷取特定叢集的所有 Pod 身分關聯，請執行下列其中一個命令：

```
eksctl get podidentityassociation -f config.yaml
```

或

```
eksctl get podidentityassociation --cluster my-cluster
```

此外，若要僅擷取指定命名空間內的 Pod 身分關聯，請使用 `--namespace`旗標，例如

```
eksctl get podidentityassociation --cluster my-cluster --namespace default
```

最後，若要擷取對應至特定 K8s 服務帳戶的單一關聯，請在上述命令中包含 `--service-account-name` ，即

```
eksctl get podidentityassociation --cluster my-cluster --namespace default --service-account-name s3-reader
```

## 更新 Pod 身分關聯
<a name="_updating_pod_identity_associations"></a>

若要更新一或多個 Pod 身分關聯的 IAM 角色，請將新的 傳遞`roleARN(s)`至組態檔案，例如

```
iam:
  podIdentityAssociations:
    - namespace: default
      serviceAccountName: s3-reader
      roleARN: new-role-arn-1
    - namespace: dev
      serviceAccountName: app-cache-access
      roleARN: new-role-arn-2
```

和 執行：

```
eksctl update podidentityassociation -f config.yaml
```

OR （更新單一關聯） `--role-arn` 透過 CLI 旗標傳遞新的 ：

```
eksctl update podidentityassociation --cluster my-cluster --namespace default --service-account-name s3-reader --role-arn new-role-arn
```

## 刪除 Pod 身分關聯
<a name="_deleting_pod_identity_associations"></a>

若要刪除一或多個 Pod 身分關聯，請將 `namespace(s)`和 傳遞`serviceAccountName(s)`至組態檔案，例如

```
iam:
  podIdentityAssociations:
    - namespace: default
      serviceAccountName: s3-reader
    - namespace: dev
      serviceAccountName: app-cache-access
```

和 執行：

```
eksctl delete podidentityassociation -f config.yaml
```

OR （若要刪除單一關聯） `--service-account-name` 透過 CLI 旗標傳遞 `--namespace`和 ：

```
eksctl delete podidentityassociation --cluster my-cluster --namespace default --service-account-name s3-reader
```

## EKS 附加元件支援 Pod 身分關聯
<a name="pod-id-support"></a>

EKS 附加元件也支援透過 EKS Pod Identity Associations 接收 IAM 許可。組態檔案會公開允許設定這些項目的三個欄位：`addon.podIdentityAssociations`、 `addonsConfig.autoApplyPodIdentityAssociations`和 `addon.useDefaultPodIdentityAssociations`。您可以使用 明確設定所需的 Pod 身分關聯，`addon.podIdentityAssociations`或使用 `addonsConfig.autoApplyPodIdentityAssociations`或 `eksctl`自動解析 （並套用） 建議的 Pod 身分組態`addon.useDefaultPodIdentityAssociations`。

**注意**  
並非所有 EKS 附加元件都會在啟動時支援 Pod 身分關聯。在此情況下，應使用 [IRSA 設定](addons.md#addons-create)繼續提供必要的 IAM 許可。

### 使用 IAM 許可建立附加元件
<a name="_creating_addons_with_iam_permissions"></a>

建立需要 IAM 許可的附加元件時， `eksctl`會先檢查 Pod 身分關聯或 IRSA 設定是否明確設定為組態檔案的一部分，如果是，請使用其中一個來設定附加元件的許可，例如

```
addons:
- name: vpc-cni
  podIdentityAssociations:
  - serviceAccountName: aws-node
    permissionPolicyARNs: ["arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy"]
```

和 執行

```
eksctl create addon -f config.yaml
2024-05-13 15:38:58 [ℹ] pod identity associations are set for "vpc-cni" addon; will use these to configure required IAM permissions
```

**注意**  
不允許同時設定 Pod 身分和 IRSA，這會導致驗證錯誤。

對於支援 Pod 身分的 EKS 附加元件， `eksctl` 提供在建立附加元件時自動設定任何建議 IAM 許可的選項。這可以透過在`addonsConfig.autoApplyPodIdentityAssociations: true`組態檔案中設定 來實現。例如，

```
addonsConfig:
  autoApplyPodIdentityAssociations: true
# bear in mind that if either pod identity or IRSA configuration is explicitly set in the config file,
# or if the addon does not support pod identities,
# addonsConfig.autoApplyPodIdentityAssociations won't have any effect.
addons:
- name: vpc-cni
```

和 執行

```
eksctl create addon -f config.yaml
2024-05-13 15:38:58 [ℹ] "addonsConfig.autoApplyPodIdentityAssociations" is set to true; will lookup recommended pod identity configuration for "vpc-cni" addon
```

同樣，也可以透過 CLI 旗標完成，例如

```
eksctl create addon --cluster my-cluster --name vpc-cni --auto-apply-pod-identity-associations
```

若要遷移現有的附加元件以搭配建議的 IAM 政策使用 Pod 身分，請使用

```
addons:
- name: vpc-cni
  useDefaultPodIdentityAssociations: true
```

```
eksctl update addon -f config.yaml
```

### 使用 IAM 許可更新附加元件
<a name="_updating_addons_with_iam_permissions"></a>

更新附加元件時，指定 `addon.PodIdentityAssociations` 會在更新操作完成後，代表附加元件應擁有之狀態的單一事實來源。在幕後，會執行不同類型的操作，以達到所需的狀態，即
+ 建立組態檔案中存在但叢集上缺少的 Pod 身分
+ 刪除從組態檔案移除的現有 Pod 身分，以及任何相關聯的 IAM 資源
+ 更新組態檔案中也存在且 IAM 許可集已變更的現有 Pod 身分

**注意**  
EKS 附加元件擁有的 Pod 身分關聯的生命週期由 EKS 附加元件 API 直接處理。

您無法針對與 Amazon EKS 附加元件搭配使用的關聯使用 `eksctl update podidentityassociation`（更新 IAM 許可） 或 `eksctl delete podidentityassociations`（移除關聯）。反之，應使用 `eksctl update addon`或 `eksctl delete addon` 。

讓我們看看上述的範例，從分析附加元件的初始 Pod 身分組態開始：

```
eksctl get podidentityassociation --cluster my-cluster --namespace opentelemetry-operator-system --output json
[
    {
        ...
        "ServiceAccountName": "adot-col-prom-metrics",
        "RoleARN": "arn:aws:iam::111122223333:role/eksctl-my-cluster-addon-adot-podident-Role1-JwrGA4mn1Ny8",
        # OwnerARN is populated when the pod identity lifecycle is handled by the EKS Addons API
        "OwnerARN": "arn:aws:eks:us-west-2:111122223333:addon/my-cluster/adot/b2c7bb45-4090-bf34-ec78-a2298b8643f6"
    },
    {
        ...
        "ServiceAccountName": "adot-col-otlp-ingest",
        "RoleARN": "arn:aws:iam::111122223333:role/eksctl-my-cluster-addon-adot-podident-Role1-Xc7qVg5fgCqr",
        "OwnerARN": "arn:aws:eks:us-west-2:111122223333:addon/my-cluster/adot/b2c7bb45-4090-bf34-ec78-a2298b8643f6"
    }
]
```

現在請使用下列組態：

```
addons:
- name: adot
  podIdentityAssociations:

  # For the first association, the permissions policy of the role will be updated
  - serviceAccountName: adot-col-prom-metrics
    permissionPolicyARNs:
    #- arn:aws:iam::aws:policy/AmazonPrometheusRemoteWriteAccess
    - arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy

  # The second association will be deleted, as it's been removed from the config file
  #- serviceAccountName: adot-col-otlp-ingest
  #  permissionPolicyARNs:
  #  - arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess

  # The third association will be created, as it's been added to the config file
  - serviceAccountName: adot-col-container-logs
    permissionPolicyARNs:
    - arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy
```

和 執行

```
eksctl update addon -f config.yaml
...
# updating the permission policy for the first association
2024-05-14 13:27:43 [ℹ]  updating IAM resources stack "eksctl-my-cluster-addon-adot-podidentityrole-adot-col-prom-metrics" for pod identity association "a-reaxk2uz1iknwazwj"
2024-05-14 13:27:44 [ℹ]  waiting for CloudFormation changeset "eksctl-opentelemetry-operator-system-adot-col-prom-metrics-update-1715682463" for stack "eksctl-my-cluster-addon-adot-podidentityrole-adot-col-prom-metrics"
2024-05-14 13:28:47 [ℹ]  waiting for CloudFormation stack "eksctl-my-cluster-addon-adot-podidentityrole-adot-col-prom-metrics"
2024-05-14 13:28:47 [ℹ]  updated IAM resources stack "eksctl-my-cluster-addon-adot-podidentityrole-adot-col-prom-metrics" for "a-reaxk2uz1iknwazwj"
# creating the IAM role for the second association
2024-05-14 13:28:48 [ℹ]  deploying stack "eksctl-my-cluster-addon-adot-podidentityrole-adot-col-container-logs"
2024-05-14 13:28:48 [ℹ]  waiting for CloudFormation stack "eksctl-my-cluster-addon-adot-podidentityrole-adot-col-container-logs"
2024-05-14 13:29:19 [ℹ]  waiting for CloudFormation stack "eksctl-my-cluster-addon-adot-podidentityrole-adot-col-container-logs"
# updating the addon, which handles the pod identity config changes behind the scenes
2024-05-14 13:29:19 [ℹ]  updating addon
# deleting the IAM role for the third association
2024-05-14 13:29:19 [ℹ]  deleting IAM resources for pod identity service account adot-col-otlp-ingest
2024-05-14 13:29:20 [ℹ]  will delete stack "eksctl-my-cluster-addon-adot-podidentityrole-adot-col-otlp-ingest"
2024-05-14 13:29:20 [ℹ]  waiting for stack "eksctl-my-cluster-addon-adot-podidentityrole-adot-col-otlp-ingest" to get deleted
2024-05-14 13:29:51 [ℹ]  waiting for CloudFormation stack "eksctl-my-cluster-addon-adot-podidentityrole-adot-col-otlp-ingest"
2024-05-14 13:29:51 [ℹ]  deleted IAM resources for addon adot
```

現在檢查 Pod 身分組態是否已正確更新

```
eksctl get podidentityassociation --cluster my-cluster --output json
[
    {
        ...
        "ServiceAccountName": "adot-col-prom-metrics",
        "RoleARN": "arn:aws:iam::111122223333:role/eksctl-my-cluster-addon-adot-podident-Role1-nQAlp0KktS2A",
        "OwnerARN": "arn:aws:eks:us-west-2:111122223333:addon/my-cluster/adot/1ec7bb63-8c4e-ca0a-f947-310c4b55052e"
    },
    {
        ...
        "ServiceAccountName": "adot-col-otlp-ingest",
        "RoleARN": "arn:aws:iam::111122223333:role/eksctl-my-cluster-addon-adot-podident-Role1-1k1XhAdziGzX",
        "OwnerARN": "arn:aws:eks:us-west-2:111122223333:addon/my-cluster/adot/1ec7bb63-8c4e-ca0a-f947-310c4b55052e"
    }
]
```

若要從附加元件移除所有 Pod 身分關聯，`addon.PodIdentityAssociations`必須明確設定為 `[]`，例如

```
addons:
- name: vpc-cni
  # omitting the `podIdentityAssociations` field from the config file,
  # instead of explicitly setting it to [], will result in a validation error
  podIdentityAssociations: []
```

和 執行

```
eksctl update addon -f config.yaml
```

### 刪除具有 IAM 許可的附加元件
<a name="_deleting_addons_with_iam_permissions"></a>

刪除附加元件也會移除與附加元件相關聯的所有 Pod 身分。刪除叢集會為所有附加元件實現相同的效果。任何由 建立之 Pod 身分的 IAM 角色`eksctl`都會正常刪除。

## 將現有的 iamserviceaccounts 和附加元件遷移至 Pod 身分關聯
<a name="_migrating_existing_iamserviceaccounts_and_addons_to_pod_identity_associations"></a>

有一個 `eksctl` utils 命令可將服務帳戶的現有 IAM 角色遷移至 Pod 身分關聯，即

```
eksctl utils migrate-to-pod-identity --cluster my-cluster --approve
```

在幕後， 命令會套用下列步驟：
+ 如果叢集上尚未處於作用中狀態，請安裝 `eks-pod-identity-agent` 附加元件
+ 識別與 iamserviceaccounts 相關聯的所有 IAM 角色
+ 識別與支援 Pod 身分關聯的 EKS 附加元件相關聯的所有 IAM 角色
+ 使用額外的信任實體，更新所有已識別角色的 IAM 信任政策，指向新的 EKS 服務主體 （並選擇性地移除執行中的 OIDC 提供者信任關係）
+ 為與 iamserviceaccounts 相關聯的篩選角色建立 Pod 身分關聯
+ 使用 Pod 身分更新 EKS 附加元件 (EKS API 會在幕後建立 Pod 身分）

在沒有`--approve`旗標的情況下執行命令只會輸出由一組反映上述步驟的任務組成的計劃，例如

```
[ℹ]  (plan) would migrate 2 iamserviceaccount(s) and 2 addon(s) to pod identity association(s) by executing the following tasks
[ℹ]  (plan)

3 sequential tasks: { install eks-pod-identity-agent addon,
    ## tasks for migrating the addons
    2 parallel sub-tasks: {
        2 sequential sub-tasks: {
            update trust policy for owned role "eksctl-my-cluster--Role1-DDuMLoeZ8weD",
            migrate addon aws-ebs-csi-driver to pod identity,
        },
        2 sequential sub-tasks: {
            update trust policy for owned role "eksctl-my-cluster--Role1-xYiPFOVp1aeI",
            migrate addon vpc-cni to pod identity,
        },
    },
    ## tasks for migrating the iamserviceaccounts
    2 parallel sub-tasks: {
        2 sequential sub-tasks: {
            update trust policy for owned role "eksctl-my-cluster--Role1-QLXqHcq9O1AR",
            create pod identity association for service account "default/sa1",
        },
        2 sequential sub-tasks: {
            update trust policy for unowned role "Unowned-Role1",
            create pod identity association for service account "default/sa2",
        },
    }
}
[ℹ]  all tasks were skipped
[!]  no changes were applied, run again with '--approve' to apply the changes
```

現有的 OIDC 提供者信任關係一律會從與 EKS 附加元件相關聯的 IAM 角色中移除。此外，若要從與 iamserviceaccounts 相關聯的 IAM 角色中移除現有的 OIDC 提供者信任關係，請使用 `--remove-oidc-provider-trust-relationship` 旗標執行 命令，例如

```
eksctl utils migrate-to-pod-identity --cluster my-cluster --approve --remove-oidc-provider-trust-relationship
```

## 跨帳戶 Pod 身分支援
<a name="_cross_account_pod_identity_support"></a>

eksctl 支援 [EKS Pod Identity 跨帳戶存取](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html)。此功能允許在 EKS 叢集中執行的 Pod 存取不同 AWS 帳戶中的 AWS 資源。

### Usage
<a name="_usage"></a>

若要建立與跨帳戶存取的 Pod 身分關聯，請先設定 IAM 角色和政策，允許從來源 AWS 帳戶 （使用叢集） 存取目標 AWS 帳戶 （使用叢集可存取的資源）。如需此範例，請參閱[「Amazon EKS Pod Identity 簡化跨帳戶存取。」](https://aws.amazon.com/blogs/containers/amazon-eks-pod-identity-streamlines-cross-account-access/) 

在每個帳戶中設定 IAM 角色後，請使用 eksctl 建立 Pod 身分關聯：

```
apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig
metadata:
  # The cluster name and service account name should match the target
  # account policy's trust relationship.
  name: my-cluster
  region: us-west-2
  version: "1.32"

addons:
  - name: vpc-cni
  - name: coredns
  - name: kube-proxy
  - name: eks-pod-identity-agent

iam:
  podIdentityAssociations:
  - namespace: default
    serviceAccountName: demo-app-sa
    createServiceAccount: true
    # The source role in the same account as the cluster
    roleARN: arn:aws:iam::1111111111:role/account-a-role
    # The target role in a different account
    targetRoleARN: arn:aws:iam::2222222222:role/account-b-role
    # Optional: Disable session tags
    disableSessionTags: false

managedNodeGroups:
  - name: my-cluster
    instanceType: m6a.large
    privateNetworking: true
    minSize: 2
    desiredCapacity: 2
    maxSize: 3
```

## 進一步參考
<a name="_further_references"></a>

 [適用於 EKS 附加元件的官方 AWS Userdocs 支援 Pod 身分](https://docs.aws.amazon.com/eks/latest/userguide/add-ons-iam.html) 

 [Pod 身分關聯的官方 AWS 部落格文章](https://aws.amazon.com/blogs/aws/amazon-eks-pod-identity-simplifies-iam-permissions-for-applications-on-amazon-eks-clusters/) 

 [Pod Identity Associations 的官方 AWS userdocs](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html) 