扩展 jstewart379 的答案:
处理此问题的基本方法是允许您的 EC2 实例以某种方式访问该存储库。
为此,您的 Gitlab 实例(不是 repo)需要公开或至少需要允许访问 EC2 实例(例如,通过修改 Gitlab 的安全组以允许端口 80 和端口443 访问 EC2 实例安全组)。
之后,您可以选择通过您的 Gitlab 实例支持的任何方法进行身份验证(这通常是 SSH 密钥或 HTTP 凭据)。
对于 SSH 密钥方法,您应该在 Gitlab 中设置只读部署密钥(不要使用您的个人 SSH 密钥)。
https://docs.gitlab.com/ee/ssh/#per-repository-deploy-keys
在此之后,您可以选择通过多种方式在实例上安装此密钥。您将使用 ASG 的用户数据选项来处理所有这些。
我的首选方法是通过加密的私有 S3 存储桶将密钥加载到实例上。
resource "aws_s3_bucket_object" "s3_object_deploy_key" {
key = "id_rsa"
bucket = "${aws_s3_bucket.s3_secrets.id}"
source = "secrets/id_rsa"
}
重要提示:请务必将该机密目录添加到您的 .gitignore 中,否则您将度过难关。
将密钥上传到存储桶后,通过 IAM 实例角色授予对该存储桶的只读访问权限。
看起来像这样:
resource "aws_iam_policy" "iam-policy-s3-deploy-key" {
name = "${var.cluster_name}-${var.env}-read-deploy-key"
path = "/"
description = "Allow reading from the S3 bucket"
policy = <<EOF
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"s3:ListBucketByTags",
"s3:GetLifecycleConfiguration",
"s3:GetBucketTagging",
"s3:GetInventoryConfiguration",
"s3:GetObjectVersionTagging",
"s3:ListBucketVersions",
"s3:GetBucketLogging",
"s3:ListBucket",
"s3:GetAccelerateConfiguration",
"s3:GetBucketPolicy",
"s3:GetObjectVersionTorrent",
"s3:GetObjectAcl",
"s3:GetEncryptionConfiguration",
"s3:GetBucketRequestPayment",
"s3:GetObjectVersionAcl",
"s3:GetObjectTagging",
"s3:GetMetricsConfiguration",
"s3:GetIpConfiguration",
"s3:ListBucketMultipartUploads",
"s3:GetBucketWebsite",
"s3:GetBucketVersioning",
"s3:GetBucketAcl",
"s3:GetBucketNotification",
"s3:GetReplicationConfiguration",
"s3:ListMultipartUploadParts",
"s3:GetObject",
"s3:GetObjectTorrent",
"s3:GetBucketCORS",
"s3:GetAnalyticsConfiguration",
"s3:GetObjectVersionForReplication",
"s3:GetBucketLocation",
"s3:GetObjectVersion"
],
"Resource":[
"${data.terraform_remote_state.secret-store.s3_secrets_arn}",
"${data.terraform_remote_state.secret-store.s3_secrets_arn}/*"
]
},
{
"Effect":"Allow",
"Action":[
"s3:ListAllMyBuckets",
"s3:HeadBucket"
],
"Resource":"*"
}
]
}
EOF
}
您将像这样设置一个实例角色并将其分配给您的启动配置:
data "aws_iam_policy_document" "instance-assume-role-policy" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
}
resource "aws_iam_role" "iam-role-instance" {
name = "${var.cluster_name}-${var.env}-instance"
path = "/system/"
assume_role_policy = "${data.aws_iam_policy_document.instance-assume-role-policy.json}"
}
resource "aws_iam_role_policy_attachment" "iam-attach-deploy-key" {
role = "${aws_iam_role.iam-role-instance.name}"
policy_arn = "${aws_iam_policy.iam-policy-s3-deploy-key.arn}"
}
获得密钥后,您可以随心所欲地使用存储库。
希望对您有所帮助!