awscli
跳转到导航
跳转到搜索
awscli是AWS官方提供的Command Line Interface(CLI)软件。
安装
可以透过pipx安装,避免影响到目前环境内的套件,目前官方建议用v2,但没有上到PyPI:
pipx install git+https://github.com/aws/aws-cli.git@v2
或是装旧的v1:
pipx install awscli
常用指令
EC2
分成两段,先是设定的部分,可以针对不同的AWS账号放到不同的档案里面用source
拉出来执行:
export AWS_PROFILE=default IMAGE_ID=ami-xxxxxxxxxxxxxxxxx INSTANCE_TYPE=t4g.small KEY_NAME=key-ed25519 NAME=test-100 PRIVATE_IP_ADDRESS=10.1.0.100 REGION=us-east-1 SECURITY_GROUP_IDS=sg-xxxxxxxxxxxxxxxxx SUBNET_ID=subnet-xxxxxxxxxxxxxxxxx
以及实际执行的部分:
aws ec2 run-instances \
--block-device-mappings "DeviceName=/dev/sda1,Ebs={VolumeType=gp3}" \
--credit-specification CpuCredits=standard \
--image-id "${IMAGE_ID}" \
--instance-type "${INSTANCE_TYPE}" \
--key-name "${KEY_NAME}" \
--network-interfaces "AssociatePublicIpAddress=true,DeviceIndex=0" \
--private-ip-address "${PRIVATE_IP_ADDRESS}" \
--region "${REGION}" \
--security-group-ids "${SECURITY_GROUP_IDS}" \
--subnet-id "${SUBNET_ID}" \
--tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${NAME}}]"
IAM
开管理员账号(这边是使用AWS内已经有的AdministratorAccess
):
aws iam create-user --user-name ${MY_AWS_USERNAME}
aws iam attach-user-policy --policy-arn arn:aws:iam::aws:policy/AdministratorAccess --user-name ${MY_AWS_USERNAME}
生出access key,一个账号最多两把。其中的AccessKeyId
与SecretAccessKey
就是需要的设定,要注意SecretAccessKey
之后不会再出现:
aws iam create-access-key --user-name ${MY_AWS_USERNAME}
超过两把再呼叫会出现错误讯息:
An error occurred (LimitExceeded) when calling the CreateAccessKey operation: Cannot exceed quota for AccessKeysPerUser: 2
列出这个账号所有的access key(只会有AccessKeyId
,不会有SecretAccessKey
):
aws iam list-access-keys --user-name ${MY_AWS_USERNAME}
S3
- 建立一个S3 bucket,
- 建立对应的使用者(IAM),
- 挂上完整的权限,
- 产生对应的key:
BUCKET_NAME=gslin-test; aws s3 mb s3://${BUCKET_NAME}; aws iam create-user --user-name s3.${BUCKET_NAME}.full; aws iam put-user-policy --user-name s3.${BUCKET_NAME}.full --policy-name Policy-s3-${BUCKET_NAME}-full --policy-document '{"Version":"2012-10-17","Statement":[{"Action":["s3:*"],"Resource":"arn:aws:s3:::'${BUCKET_NAME}'/*","Effect":"Allow"}]}'; aws iam create-access-key --user-name s3.${BUCKET_NAME}.full
如果是只能读取的话,这边列出比较常见的操作("s3:GetObject","s3:HeadObject","s3:ListObjects","s3:ListObjectsV2"
这段):
BUCKET_NAME=gslin-test; aws s3 mb s3://${BUCKET_NAME}; aws iam create-user --user-name s3.${BUCKET_NAME}.readonly; aws iam put-user-policy --user-name s3.${BUCKET_NAME}.readonly --policy-name Policy-s3-${BUCKET_NAME}-readonly --policy-document '{"Version":"2012-10-17","Statement":[{"Action":["s3:GetObject","s3:HeadObject","s3:ListObjects","s3:ListObjectsV2"],"Resource":"arn:aws:s3:::'${BUCKET_NAME}'/*","Effect":"Allow"}]}'; aws iam create-access-key --user-name s3.${BUCKET_NAME}.readonly