Skip to content

Commit 78aa2df

Browse files
authored
Merge pull request #31 from maddevsio/feature/variables-cleanup
Minor fixes in variables, locals, r53 zone etc
2 parents 3beeea2 + fcb45ce commit 78aa2df

25 files changed

+329
-196
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ crash.log
6262
# version control.
6363
#
6464
**/*.tfvars
65+
**/backend.tf
6566

6667
# Ignore override files as they are usually used to override resources locally and so
6768
# are not checked in

README-RU.md

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -224,53 +224,62 @@
224224
$ export AWS_PROFILE=maddevs
225225
```
226226
- Далее пройдите по [ссылке](https://docs.aws.amazon.com/neptune/latest/userguide/iam-auth-temporary-credentials.html), чтобы узнать как получить временные токены
227-
- В качетве альтернативы, для того чтобы использовать `awscli` и соответственно `terraform` с [MFA](https://aws.amazon.com/premiumsupport/knowledge-center/authenticate-mfa-cli/), можно использовать `aws-mfa`, `aws-vault` и `awsudo`
227+
- В качестве альтернативы, для того чтобы использовать `awscli` и соответственно `terraform` с [MFA](https://aws.amazon.com/premiumsupport/knowledge-center/authenticate-mfa-cli/), можно использовать `aws-mfa`, `aws-vault` и `awsudo`
228228

229229
## Как использовать этот репо
230230

231231
### Подготовка
232232

233233
#### S3 state backend
234234

235-
В качестве бэкенда для хранения стейтов терраформа и для обмена данными между слоями используется S3. На текущей момент имя S3 бакета захардкожено в коде `madops-terraform-state-us-east-1`. Необходимо создать отдельный бакет в своем аккаунте указать его имя в `main.tf` для обоих слоев.
235+
В качестве бэкенда для хранения стейтов терраформа и для обмена данными между слоями используется S3. Есть два способа настроить бэкенд: создать вручную `backend.tf` файл в каждом слое и более простой способ - выполнить из `terraform/`:
236236

237-
#### Секреты
237+
```bash
238+
$ export TF_REMOTE_STATE_BUCKET=my-new-state-bucket
239+
$ terragrunt run-all init
240+
```
238241

239-
В корне `layer2-k8s` лежит файл `aws-ssm-gitlab-secrets.tf`, ожидающий значения, заданные в AWS SSM Parameter Store. Данные секреты используются для аутентификации в Kibana и Grafana используя GitLab. Также в параметрах задается токен для регистрации гитлаб раннера:
242+
#### Входные данные
240243

241-
```
242-
/maddevs-demo/infra/grafana/gitlab_client_id
243-
/maddevs-demo/infra/grafana/gitlab_client_secret
244-
/maddevs-demo/infra/kibana/gitlab_client_id
245-
/maddevs-demo/infra/kibana/gitlab_client_secret
246-
/maddevs-demo/infra/runner/gitlab_registration_token
247-
```
244+
В файле `terraform/demo.tfvars.example` представлен пример со значениями для терраформа. Скопируйте его в `terraform/terraform.tfvars` и отредактируйте по своему усмотрению:
245+
246+
```bash
247+
$ cp terraform/layer1-aws/demo.tfvars.example terraform/layer1-aws/terraform.tfvars
248+
```
249+
250+
> Все возможные параметры можно посмотреть в Readme для каждого слоя.
251+
252+
#### Секреты
248253

249-
Другой способ передачи этих секретов - использовать AWS Secret Manager. В файле `examples/aws-secret-manager-gitlab-secrets.tf` находится пример использования. Данный конфиг ожидает json секрет `/maddevs-demo/infra/gitlab-tokens` с содержимым:
254+
В корне `layer2-k8s` лежит файл `aws-sm-secrets.tf`, ожидающий значения, заданные в секрете `/${local.name}-${local.environment}/infra/layer2-k8s` сервиса [AWS Secrets Manager](https://console.aws.amazon.com/secretsmanager/home?region=us-east-1#!/home). Данный секрет используется для аутентификации в Kibana и Grafana используя GitLab. Также задается токен для регистрации гитлаб раннера, параметры slack для алертменеджера:
250255

251256
```json
252257
{
253258
"kibana_gitlab_client_id": "access key token",
254259
"kibana_gitlab_client_secret": "secret key token",
260+
"kibana_gitlab_group": "gitlab group",
255261
"grafana_gitlab_client_id": "access key token",
256262
"grafana_gitlab_client_secret": "secret key token",
257-
"gitlab_registration_token": "gitlab-runner token"
263+
"gitlab_registration_token": "gitlab-runner token",
264+
"grafana_gitlab_group": "gitlab group",
265+
"alertmanager_slack_url": "slack url",
266+
"alertmanager_slack_channel": "slack channel"
258267
}
259268
```
260269

261-
Используя тот или иной способ, задайте необходимые секреты, можно задать пустые значения. В случае если вы не будете использовать данные секреты, следует удалить эти `.tf` файлы из корня `layer2-k8s`
270+
> Задайте все необходимые значения, можно задать пустые значения. В случае если вы не будете использовать данные секреты, следует удалить этот `.tf` файл из корня `layer2-k8s`
262271
263272
#### Домен и SSL
264273

265274
Необходимо будет купить или подключить уже купленный домен в Route53. Имя домена и айди зоны нужно будет задать в переменных `domain_name` и `zone_id` в слое layer1.
266275

267-
По умолчанию значение переменной `create_acm_certificate = false`. Что указывает терраформу запросить а arn существующего ACM сертификата. Установите значение `true` если вы хотите, чтобы терраформ создал новый SSL сертификат.
276+
По умолчанию значение переменной `create_acm_certificate = false`. Что указывает терраформу запросить arn существующего ACM сертификата. Установите значение `true` если вы хотите, чтобы терраформ создал новый SSL сертификат.
268277

269278
### Работа с terraform
270279

271280
#### init
272281

273-
Команда `terraform init` используется для инициализации стейта и его бекенда, провайдеров, плагинов и модулей. Это первая команда, которую необходимо выполнить в `layer1` и `layer2`:
282+
Команда `terraform init` используется для инициализации стейта и его бэкенда, провайдеров, плагинов и модулей. Это первая команда, которую необходимо выполнить в `layer1` и `layer2`:
274283

275284
```bash
276285
$ terraform init

README.md

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -230,33 +230,42 @@ Further in the [IAM](https://console.aws.amazon.com/iam/home#/home) console:
230230

231231
#### S3 state backend
232232

233-
S3 is used as a backend for storing terraform states and for exchanging data between layers. Currently, the name of the S3 bucket is hardcoded as `madops-terraform-state-us-east-1`. You need to create a separate bucket in your account and specify its name in `main.tf` for both layers.
233+
S3 is used as a backend for storing terraform state and for exchanging data between layers. You can manually create s3 bucket and then put backend setting into `backend.tf` file in each layer. Alternatively you can run from `terraform/` directory:
234234

235-
#### Secrets
235+
```bash
236+
$ export TF_REMOTE_STATE_BUCKET=my-new-state-bucket
237+
$ terragrunt run-all init
238+
```
236239

237-
At the root of `layer2-k8s` is the `aws-ssm-gitlab-secrets.tf` file waiting for values set in the AWS SSM Parameter Store. These secrets are used for authentication with Kibana and Grafana using GitLab. Also, in the parameters, a token is set for registering a gitlab runner:
240+
#### Inputs
238241

239-
```
240-
/maddevs-demo/infra/grafana/gitlab_client_id
241-
/maddevs-demo/infra/grafana/gitlab_client_secret
242-
/maddevs-demo/infra/kibana/gitlab_client_id
243-
/maddevs-demo/infra/kibana/gitlab_client_secret
244-
/maddevs-demo/infra/runner/gitlab_registration_token
245-
```
242+
File `terraform/layer1-aws/demo.tfvars.example` contains example values. Copy this file to `terraform/layer1-aws/terraform.tfvars` and set you values:
243+
244+
```bash
245+
$ cp terraform/layer1-aws/demo.tfvars.example terraform/layer1-aws/terraform.tfvars
246+
```
247+
248+
> You can find all possible variables in each layer's Readme.
249+
250+
#### Secrets
246251

247-
Another way to set these secrets is to use AWS Secret Manager. The `examples/aws-secret-manager-gitlab-secrets.tf` file contains an example of usage. This config expects json secret `/maddevs-demo/infra/gitlab-tokens` with the following content:
252+
In the root of `layer2-k8s` is the `aws-sm-secrets.tf` where several local variables expect [AWS Secrets Manager](https://console.aws.amazon.com/secretsmanager/home?region=us-east-1#!/home) secret with the pattern `/${local.name}-${local.environment}/infra/layer2-k8s`. These secrets are used for authentication with Kibana and Grafana using GitLab and register gitlab runner.
248253

249254
```json
250255
{
251256
"kibana_gitlab_client_id": "access key token",
252257
"kibana_gitlab_client_secret": "secret key token",
258+
"kibana_gitlab_group": "gitlab group",
253259
"grafana_gitlab_client_id": "access key token",
254260
"grafana_gitlab_client_secret": "secret key token",
255-
"gitlab_registration_token": "gitlab-runner token"
261+
"gitlab_registration_token": "gitlab-runner token",
262+
"grafana_gitlab_group": "gitlab group",
263+
"alertmanager_slack_url": "slack url",
264+
"alertmanager_slack_channel": "slack channel"
256265
}
257266
```
258267

259-
Using either of these methods, set proper secrets; you can set empty values. If you will not use these secrets, you should delete these `.tf` files from the `layer2-k8s` root.
268+
> Set proper secrets; you can set empty/mock values. If you won't use these secrets, delete this `.tf` file from the `layer2-k8s` root.
260269
261270
#### Domain and SSL
262271

@@ -288,7 +297,7 @@ The `terraform init` command is used to initialize the state and its backend, do
288297

289298
#### plan
290299

291-
The `terraform plan` command reads the terraform state and configuration files and displays a list of changes and actions that need to be performed to bring the state in line with the configuration. It's a convenient way to test changes before applying them. When used with the `-out` parameter, it saves a batch of changes to a specified file that can later be used with `terraform apply`. Call example:
300+
The `terraform plan` command reads terraform state and configuration files and displays a list of changes and actions that need to be performed to bring the state in line with the configuration. It's a convenient way to test changes before applying them. When used with the `-out` parameter, it saves a batch of changes to a specified file that can later be used with `terraform apply`. Call example:
292301

293302
```bash
294303
$ terraform plan

terraform/layer1-aws/README.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
## Requirements
2+
3+
| Name | Version |
4+
|------|---------|
5+
| terraform | ~> 0.14.6 |
6+
| aws | 3.26.0 |
7+
| kubernetes | 2.0.2 |
8+
9+
## Providers
10+
11+
| Name | Version |
12+
|------|---------|
13+
| aws | 3.26.0 |
14+
15+
## Inputs
16+
17+
| Name | Description | Type | Default | Required |
18+
|------|-------------|------|---------|:--------:|
19+
| allowed\_account\_ids | List of allowed AWS account IDs | `list` | `[]` | no |
20+
| allowed\_ips | IP addresses allowed to connect to private resources | `list(any)` | `[]` | no |
21+
| az\_count | Count of avaiablity zones, min 2 | `number` | `3` | no |
22+
| cidr | Default CIDR block for VPC | `string` | `"10.0.0.0/16"` | no |
23+
| create\_acm\_certificate | Whether to create acm certificate or use existing | `bool` | `false` | no |
24+
| create\_r53\_zone | Create R53 zone for main public domain | `bool` | `false` | no |
25+
| domain\_name | Main public domain name | `any` | n/a | yes |
26+
| ecr\_repo\_retention\_count | number of images to store in ECR | `number` | `50` | no |
27+
| ecr\_repos | List of docker repositories | `list(any)` | <pre>[<br> "demo"<br>]</pre> | no |
28+
| eks\_cluster\_version | Version of the EKS K8S cluster | `string` | `"1.18"` | no |
29+
| eks\_map\_roles | Additional IAM roles to add to the aws-auth configmap. | <pre>list(object({<br> rolearn = string<br> username = string<br> groups = list(string)<br> }))</pre> | `[]` | no |
30+
| eks\_worker\_groups | EKS Worker groups configuration | `map` | <pre>{<br> "ci": {<br> "asg_desired_capacity": 0,<br> "asg_max_size": 3,<br> "asg_min_size": 0,<br> "override_instance_types": [<br> "t3.medium",<br> "t3a.medium"<br> ],<br> "spot_instance_pools": 2<br> },<br> "ondemand": {<br> "asg_desired_capacity": 1,<br> "asg_max_size": 6,<br> "instance_type": "t3a.medium"<br> },<br> "spot": {<br> "asg_desired_capacity": 1,<br> "asg_max_size": 5,<br> "asg_min_size": 0,<br> "override_instance_types": [<br> "t3.medium",<br> "t3a.medium"<br> ],<br> "spot_instance_pools": 2<br> }<br>}</pre> | no |
31+
| eks\_write\_kubeconfig | Flag for eks module to write kubeconfig | `bool` | `false` | no |
32+
| environment | Env name in case workspace wasn't used | `string` | `"demo"` | no |
33+
| name | Project name, required to form unique resource names | `any` | n/a | yes |
34+
| region | Default infrastructure region | `string` | `"us-east-1"` | no |
35+
| short\_region | The abbreviated name of the region, required to form unique resource names | `map` | <pre>{<br> "ap-east-1": "ape1",<br> "ap-northeast-1": "apn1",<br> "ap-northeast-2": "apn2",<br> "ap-south-1": "aps1",<br> "ap-southeast-1": "apse1",<br> "ap-southeast-2": "apse2",<br> "ca-central-1": "cac1",<br> "cn-north-1": "cnn1",<br> "cn-northwest-1": "cnnw1",<br> "eu-central-1": "euc1",<br> "eu-north-1": "eun1",<br> "eu-west-1": "euw1",<br> "eu-west-2": "euw2",<br> "eu-west-3": "euw3",<br> "sa-east-1": "sae1",<br> "us-east-1": "use1",<br> "us-east-2": "use2",<br> "us-gov-east-1": "usge1",<br> "us-gov-west-1": "usgw1",<br> "us-west-1": "usw1",<br> "us-west-2": "usw2"<br>}</pre> | no |
36+
| single\_nat\_gateway | Flag to create single nat gateway for all AZs | `bool` | `true` | no |
37+
| zone\_id | R53 zone id for public domain | `any` | `null` | no |
38+
39+
## Outputs
40+
41+
| Name | Description |
42+
|------|-------------|
43+
| allowed\_ips | List of allowed ip's, used for direct ssh access to instances. |
44+
| az\_count | Count of avaiablity zones, min 2 |
45+
| domain\_name | Domain name |
46+
| eks\_cluster\_endpoint | Endpoint for EKS control plane. |
47+
| eks\_cluster\_id | n/a |
48+
| eks\_cluster\_security\_group\_id | Security group ids attached to the cluster control plane. |
49+
| eks\_config\_map\_aws\_auth | A kubernetes configuration to authenticate to this EKS cluster. |
50+
| eks\_kubectl\_config | kubectl config as generated by the module. |
51+
| eks\_kubectl\_console\_config | description |
52+
| eks\_oidc\_provider\_arn | ARN of EKS oidc provider |
53+
| env | Suffix for the hostname depending on workspace |
54+
| name | Project name, required to form unique resource names |
55+
| name\_wo\_region | Project name, required to form unique resource names without short region |
56+
| region | Target region for all infrastructure resources |
57+
| route53\_zone\_id | ID of domain zone |
58+
| short\_region | The abbreviated name of the region, required to form unique resource names |
59+
| ssl\_certificate\_arn | ARN of SSL certificate |
60+
| vpc\_cidr | CIDR block of infra VPC |
61+
| vpc\_database\_subnets | Database subnets of infra VPC |
62+
| vpc\_id | ID of infra VPC |
63+
| vpc\_intra\_subnets | Private intra subnets |
64+
| vpc\_name | Name of infra VPC |
65+
| vpc\_private\_subnets | Private subnets of infra VPC |
66+
| vpc\_public\_subnets | Public subnets of infra VPC |
67+

terraform/layer1-aws/aws-acm.tf

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ module "acm" {
66

77
domain_name = local.domain_name
88
subject_alternative_names = ["*.${local.domain_name}"]
9-
zone_id = var.zone_id
9+
zone_id = local.zone_id
1010

1111
tags = {
1212
Name = local.name

terraform/layer1-aws/aws-eks.tf

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ module "eks" {
9494
},
9595
]
9696

97-
map_roles = var.map_roles
97+
map_roles = local.eks_map_roles
9898

99-
write_kubeconfig = false
99+
write_kubeconfig = var.eks_write_kubeconfig
100100
}

terraform/layer1-aws/aws-r53.tf

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
module "r53_zone" {
2+
source = "terraform-aws-modules/route53/aws//modules/zones"
3+
version = "~> 1.9.0"
4+
5+
create = var.create_r53_zone
6+
7+
zones = {
8+
(var.domain_name) = {
9+
comment = var.domain_name
10+
tags = {
11+
Name = local.name
12+
Environment = local.env
13+
}
14+
}
15+
}
16+
}
17+
18+
data "aws_route53_zone" "main" {
19+
count = var.create_r53_zone && var.zone_id == null ? 0 : 1
20+
21+
name = "${var.domain_name}."
22+
private_zone = false
23+
}

terraform/layer1-aws/aws-vpc.tf

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,8 @@ module "vpc" {
2323
database_subnets = local.database_subnets
2424
intra_subnets = local.intra_subnets
2525

26-
26+
single_nat_gateway = var.single_nat_gateway
2727
enable_nat_gateway = true
28-
single_nat_gateway = true
2928
enable_vpn_gateway = false
3029
enable_dns_hostnames = true
3130
enable_dns_support = true

terraform/layer1-aws/backend.tf

Lines changed: 0 additions & 10 deletions
This file was deleted.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
##########
2+
# Common
3+
##########
4+
name = "example"
5+
domain_name = "example.org"
6+
environment = "demo"
7+
8+
##########
9+
# Network
10+
##########
11+
region = "us-east-1"
12+
az_count = 3
13+
allowed_ips = [
14+
"0.0.0.0/0"
15+
]
16+
single_nat_gateway = true
17+
18+
##########
19+
# EKS
20+
##########
21+
eks_cluster_version = "1.18"
22+
23+
eks_worker_groups = {
24+
spot = {
25+
override_instance_types = ["t3.medium", "t3a.medium"]
26+
spot_instance_pools = 2
27+
asg_max_size = 5
28+
asg_min_size = 0
29+
asg_desired_capacity = 1
30+
},
31+
ondemand = {
32+
instance_type = "t3a.medium"
33+
asg_desired_capacity = 1
34+
asg_max_size = 6
35+
},
36+
ci = {
37+
override_instance_types = ["t3.medium", "t3a.medium"]
38+
spot_instance_pools = 2
39+
asg_max_size = 3
40+
asg_min_size = 0
41+
asg_desired_capacity = 0
42+
}
43+
}
44+
45+
eks_write_kubeconfig = false

0 commit comments

Comments
 (0)