Skip to content

Instantly share code, notes, and snippets.

@LozanoMatheus
Last active January 22, 2021 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LozanoMatheus/a41ee2f04d8232b7c33c08991e31832b to your computer and use it in GitHub Desktop.
Save LozanoMatheus/a41ee2f04d8232b7c33c08991e31832b to your computer and use it in GitHub Desktop.
Using AWS IAM Role in a EKS / Kubernetes POD
## First of all, check if you already have an OpenID Connect
### List your EKS cluster OIDC URL
aws eks describe-cluster --name <CLUSTER_NAME> --query "cluster.identity.oidc.issuer"
#### Output
https://oidc.eks.<REGION>.amazonaws.com/id/<OIDC_ID>
### List your
aws iam list-open-id-connect-providers
#### The output shouldn't contain any provider with the same <OIDC_ID> listed in the previous command
{
"OpenIDConnectProviderList": []
}
#### OR
{
"OpenIDConnectProviderList": [
{
"Arn": "arn:aws:iam::<ACCOUNT_ID>:oidc-provider/oidc.eks.<REGION>.amazonaws.com/id/<ANOTHER_OIDC_ID>"
}
]
}
## Create this only if you don't have an OpenID Connect provider for the cluster
eksctl utils associate-iam-oidc-provider --cluster <CLUSTER_NAME> --approve
## Now it's time to create the AWS IAM Role (<ROLE_NAME>), a Kubernetes ServiceAccount
## and attach an pre-existing IAM Policy (<POLICY_NAME>) into the new role (<ROLE_NAME>)
## The IAM role will be created by the eksctl and attach the pre-existing policy (<POLICY_NAME>) into it.
eksctl create iamserviceaccount \
--cluster=<CLUSTER_NAME> \
--role-name=<ROLE_NAME> \
--namespace=<NAMESPACE> \
--name=<SERVICE_ACCOUNT_NAME> \
--attach-policy-arn=<POLICY_NAME> \
--approve
## In the spec, we'll provide the <SERVICE_ACCOUNT_NAME> created previously.
kubectl apply -f- <<EOF
apiVersion: v1
kind: Pod
metadata:
name: amazonlinux
namespace: <NAMESPACE>
spec:
serviceAccountName: <SERVICE_ACCOUNT_NAME>
containers:
- name: amazonlinux
image: amazonlinux
command: [ "sh", "-c", "sleep 8h" ]
EOF
## Delete the new AWS IAM Role and the Kubernetes ServiceAccount
eksctl delete iamserviceaccount \
--cluster=<CLUSTER_NAME> \
--namespace=<NAMESPACE> \
--name=<SERVICE_ACCOUNT_NAME>
#### BE CAREFUL ####
## There is no way to delete an OpenID Connect via eksctl. https://github.com/weaveworks/eksctl/issues/1653
### To delete, you'll need to get the OIDC ARN
#### BE CAREFUL ####
aws iam list-open-id-connect-providers
## Now, get the ARN and delete the OIDC provider
#### BE CAREFUL ####
aws iam delete-open-id-connect-provider --open-id-connect-provider-arn <OPEN_ID_CONNECT_PROVIDERS_ARN>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment