{"id":21812831,"url":"https://github.com/gforien/terraform-examples","last_synced_at":"2026-05-07T13:46:59.161Z","repository":{"id":46295893,"uuid":"422621285","full_name":"gforien/terraform-examples","owner":"gforien","description":"Provision AWS EC2 instances in no time with Terraform 👨‍💻⏭🕖","archived":false,"fork":false,"pushed_at":"2021-12-14T11:05:08.000Z","size":42,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-19T02:48:06.134Z","etag":null,"topics":["aws-ec2","devops","infrastructure-as-code","terraform"],"latest_commit_sha":null,"homepage":"","language":"Shell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gforien.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-10-29T15:14:51.000Z","updated_at":"2021-12-14T11:05:11.000Z","dependencies_parsed_at":"2022-08-18T21:51:10.618Z","dependency_job_id":null,"html_url":"https://github.com/gforien/terraform-examples","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/gforien/terraform-examples","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gforien%2Fterraform-examples","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gforien%2Fterraform-examples/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gforien%2Fterraform-examples/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gforien%2Fterraform-examples/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gforien","download_url":"https://codeload.github.com/gforien/terraform-examples/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gforien%2Fterraform-examples/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261601480,"owners_count":23183092,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws-ec2","devops","infrastructure-as-code","terraform"],"created_at":"2024-11-27T14:20:33.496Z","updated_at":"2026-05-07T13:46:56.644Z","avatar_url":"https://github.com/gforien.png","language":"Shell","funding_links":[],"categories":[],"sub_categories":[],"readme":"# terraform-examples\n\n## Introduction\nDéployer une configuration avec Terraform =\n- **Scope** - Identify the infrastructure for your project.\n- **Author** - Write the configuration for your infrastructure.\n- **Initialize** - Install the plugins Terraform needs to manage the infrastructure.\n- **Plan** - Preview the changes Terraform will make to match your configuration.\n- **Apply** - Make the planned changes.\n\nL'état de l'infrastructure à un instant T est contenu dans le **state file**.\nLe statefile est confidnetiel. On ne le commit pas, mais on le stocke dans un endroit\nsécurisé, et tous les développeurs ne doivent pas y avoir accès.\nTerraform vend son Terraform Cloud pour hoster les statefiles justement.\n\nUne configuration Terraform s'appelle aussi un *module*.\u003cbr\u003e\nTerraform est **déclaratif**, pas procédural.\u003cbr\u003e\nUn gitignore est disponible\n[ici](https://github.com/github/gitignore/blob/master/Terraform.gitignore)\n\n\n\n## 1. terraform-docker example\n\n- `tf plan`  pour afficher son *execution plan*\n- `tf apply -auto-approve` pour apply et créer\u003cbr\u003e\n  Les données qui ne sont pas connues d'avance sont récupérées par terraform pendant\n  l'apply et écrites comme le reste dans le **state file**.\n\n- `tf apply -auto-approve -destroy` pour apply et détruire\n```sh\n$ tf apply -auto-approve\n\nTerraform used the selected providers to generate the following execution plan.\nResource actions are indicated with the following symbols:\n  + create\n\nTerraform will perform the following actions:\n\n  # docker_container.nginx will be created\n  + resource \"docker_container\" \"nginx\" {\n      + attach           = false\n      + tty              = false\n        ...\n\n      + healthcheck { ... }\n\n      + labels { ... }\n\n      + ports {\n          + external = 8000\n          + internal = 80\n          + ip       = \"0.0.0.0\"\n          + protocol = \"tcp\"\n        }\n    }\n\n  # docker_image.nginx will be created\n  + resource \"docker_image\" \"nginx\" {\n      + id           = (known after apply)\n      + keep_locally = false\n      + latest       = (known after apply)\n      + name         = \"nginx:latest\"\n      + output       = (known after apply)\n      + repo_digest  = (known after apply)\n    }\n\nPlan: 2 to add, 0 to change, 0 to destroy.\n\nDo you want to perform these actions?\n  Terraform will perform the actions described above.\n  Only 'yes' will be accepted to approve.\n\n  Enter a value: yes\n\ndocker_image.nginx: Creating...\ndocker_image.nginx: Creation complete after 1m50s\n\u003e [id=sha256:87a94228f133e2da99cb16d653cd1373c5b4e8689956386c1c12b60a20421a02nginx:latest]\ndocker_container.nginx: Creating...\ndocker_container.nginx: Creation complete after 2s\n\u003e [id=f6ab78bc1115213fce860f4f73f2fa05051b8eef2d23cf0cd31a76671389898a]\n\nApply complete! Resources: 2 added, 0 changed, 0 destroyed.\n```\n\nChaque configuration terraform doit avoir son dossier.\nQuand on crée ou qu'on checkout une nouvelle configuration, il faut faire `tf init` avant\ntout. `tf init` télécharge les providers dans le répertoire caché `.terraform/` avec une\ncertaine version.\n\nLe fichier main.tf a au moins 3 sections:\n- `terraform`: les paramètres Terraform donc notamment les `required_providers`.\u003cbr\u003e\n  Les providers sont installés à partir du\n  [Terraform Registry](https://registry.terraform.io/) par défaut, donc `aws` ==\n  `registry.terraform.io/aws`,\n  (comme pour une image docker où `nginx` == `docker.io/library/nginx`).\n\n- `provider`: les paramètres du provider. Le provider est le plugin permettant de créer\n  et manager les ressources. C'est lui qui définit les types de ressources possibles.\n  Par exemple `docker` permet les types `docker_image` et `docker_container`.\n\n- `resource`. Une ressource peut être un container, une application, un VPC...\n  La ressource a un type et son nom. Il faut ensuite voir dans les spécifications des\n  providers pour savoir quel paramètre attend quel type de ressource.\n\nAWS, GCP et Azure ne fournissent finalement qu'un ensemble de ressources (de différentes\nnatures) qui sont autant de briques à assembler dans Terraform.\n\nOutils:\n- `tf fmt` réindente correctement, et renvoie le noms des fichiers corrigés. Si tout est\n  bien formaté il ne renvoie rien.\n- `tf validate`\n- `tf show`       lit le `terraform.tfstate` et l'affiche un peu différemment\n- `tf state list` pour lister les ressources\n- `tf state show XXXXX` pour afficher une ressource\n\n### Variables\nOn ajoute un fichier `variables.tf` qui contient des blocs variables.\u003cbr\u003e\nTous les fichiers `.tf` sont chargés quelque soit leur nom.\n\nUne variable a un type, une description, et éventuellement une valeur par défaut.\n```terraform\nvariable \"hello\" {\n    type        = string\n    description = \"...\"\n    default     = \"...\"\n}\n```\n\nOn peut passer les variables en ligne de commande\n```sh\ntf plan  -var \"container_name=YetAnotherName\"\ntf apply -var \"container_name=YetAnotherName\"\n```\n\n### Outputs\nOn ajoute un fichier `outputs.tf` qui contient les blocs outputs.\u003cbr\u003e\nUn output a une description et une valeur à partir des ressources dans `main.tf`.\n```terraform\noutput \"hello\" {\n    description = \"...\"\n    value       = docker_resource.id\n}\n```\n\n### Un cycle complet avec terraform-cli\n```sh\n# créer\ntf init\ntf init -upgrade                    # si modifications du provider\ntf fmt\ntf validate\ntf plan                             # -var 'a=b' -var 'b=c' en option\ntf apply -auto-approve              # -var 'a=b' -var 'b=c' en option\n\n# inspecter l'état actuel\ntf plan                             # fait refresh et affiche les modifications\ntf refresh \u0026\u0026 tf show               # fait refresh et affiche 'terraform.tfstate' au format HCL\ntf state list\ntf state show my_ec2\n\n# détruire\ntf apply -auto-approve -destroy     # -var 'a=b' -var 'b=c' en option\n```\n\n**Note sur `refresh`**\nLe but long-terme est que seuls terraform `plan` et `apply` soient nécessaires (voir\n[cette issue](https://github.com/hashicorp/terraform/issues/26093)).\u003cbr\u003e\n`refresh` n'affiche donc pas les modifications, mais `plan` et `apply` font automatiquement\nun refresh et affichent les modifications d'état.\n\n### Provisionner des VM / des containers\nPour provisionner des VM :\n- on peut partir du SDK d'un provider, et écrire notre logiciel par-dessus\n- on peut partir l'outil CLI d'un provider, et écrire notre script par-dessus\n- on peut utiliser Terraform 🔥\nUn intérêt d'utiliser Terraform est donc de ne pas avoir à gérer nous-même la multitude\nde configurations possibles à faire pour déployer une architecture sur différents clouds.\n**On éloigne le problème du vendor lock-in.**\n\nL'intérêt de provisionner des VM avec Terraform est clair.\u003cbr\u003e\nMais qu'en est-il des containers Docker ?\n\n\u003e Pourquoi provisionner des containers via Terraform quand on peut faire pareil avec\nun orchestrateur qui est fait pour ?\n\n**→ Aucun. On ne déploie pas des pods ou des containers avec terraform.**\u003cbr\u003e\nOn déploie uniquement le cluster Kubernetes, et par exemple notre registry de\npackages Kubernetes (comme Helm). Ensuite on laisse Kubernetes s'occuper de\ndéployer notre infrastructure.\n\nVoir aussi\n- https://blog.zwindler.fr/talks/osxp-2021-ciel-mon-kube-mine-bitcoins/\n- https://blog.zwindler.fr/2018/02/06/se-simplifier-kubernetes-helm-charts/\n\n\n\n## 3. terraform-aws-full-ec2 example\n\n📚 **Sources**\n- **aug.2020** → [hashicorp/aws/two-tier/main.tf](https://github.com/hashicorp/terraform-provider-aws/blob/main/examples/two-tier/main.tf)\n- **oct. 2021** → [josh-tracy/tf-helm-eks-jenkins/main.tf](https://github.com/Josh-Tracy/Terraform-Helm-EKS-Jenkins/blob/main/main.tf)\n\n### Lien entre AWS et Terraform\nIl faut avoir fait `aws configure` et entré sa clé d'accès avec les bonnes permissions.\u003cbr\u003e\nDans la section `provider \"aws\" {}` on précise `profile = \"default\"`.\n\n### Steps\n1. Créer le VPC et ce qui en dépend (IG, Route table, SG)\n2. Créer le subnet et ce qui en dépend (NIC, Route table association)\n\n\nVoir aussi https://github.com/gnokoheat/ecs-with-codepipeline-example-by-terraform\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgforien%2Fterraform-examples","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgforien%2Fterraform-examples","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgforien%2Fterraform-examples/lists"}