[
  {
    "path": ".github/workflows/linkchecker.yml",
    "content": "name: Link-Checker\n\non: pull_request\n\njobs:\n  check:\n\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v2\n    - name: Set up Ruby 2.7\n      uses: actions/setup-ruby@v1\n      with:\n        ruby-version: 2.7\n    - name: Check project links\n      run: |\n        gem install awesome_bot\n        awesome_bot README.md --allow-redirect --allow-dupe --allow 429 -w .amazonaws.com,news.ycombinator.com,swagger.io,www.amazon.com\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: ruby\nrvm: 2.2\nbefore_script: gem install awesome_bot\nscript: awesome_bot README.md --allow-redirect --allow-dupe --allow 429 -w .amazonaws.com,news.ycombinator.com,swagger.io\n"
  },
  {
    "path": "AUTHORS.md",
    "content": "# Authors\n\nThis “Open Guide” is a collaborative effort.\nIt was begun and is led by [@jlevy](https://github.com/jlevy) and [@ThanosBaskous](https://github.com/ThanosBaskous),\nbut the content is the result of a community of contributors, editors, and experts.\nPlease help if you can. See the [contribution guidelines](CONTRIBUTING.md) for notes on roles and editorial process.\n\n\n\n*Leads*\n\n* [Joshua Levy (jlevy)](https://github.com/jlevy) — [120+](https://github.com/open-guides/og-aws/commits?author=jlevy)/[129+](https://github.com/open-guides/og-aws/issues?q=author%3Ajlevy) — _project lead, editor (topics not otherwise assigned)_\n* [Corey Quinn (QuinnyPig)](https://github.com/QuinnyPig) — [59+](https://github.com/open-guides/og-aws/commits?author=QuinnyPig)/[59+](https://github.com/open-guides/og-aws/issues?q=author%3AQuinnyPig) — _community lead, editor (news and updates, cost management)_\n* [Thanos Baskous (ThanosBaskous)](https://github.com/ThanosBaskous) — [39+](https://github.com/open-guides/og-aws/commits?author=ThanosBaskous)/[39+](https://github.com/open-guides/og-aws/issues?q=author%3AThanosBaskous) — _project lead, editor (topics not otherwise assigned)_\n\n*Editors and Experts*\n\n* [Artem Nikitin (artemnikitin)](https://github.com/artemnikitin) — [15+](https://github.com/open-guides/og-aws/commits?author=artemnikitin)/[11+](https://github.com/open-guides/og-aws/issues?q=author%3Aartemnikitin) — _editor (Certificate Manager)_\n* [Ben Kehoe (benkehoe)](https://github.com/benkehoe) — [4+](https://github.com/open-guides/og-aws/commits?author=benkehoe)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Abenkehoe) — _expert (IoT)_\n* [Bogdan Luput (bgdnlp)](https://github.com/bgdnlp) — [11+](https://github.com/open-guides/og-aws/commits?author=bgdnlp)/[10+](https://github.com/open-guides/og-aws/issues?q=author%3Abgdnlp) — _editor (EFS)_\n* [Dan Hermann (danhermann)](https://github.com/danhermann) — [5+](https://github.com/open-guides/og-aws/commits?author=danhermann)/[7+](https://github.com/open-guides/og-aws/issues?q=author%3Adanhermann) — _expert (RDS)_\n* [Donne Martin (donnemartin)](https://github.com/donnemartin) — _expert (tools)_\n* [Eric Hammond (ehammond)](https://github.com/ehammond) — _expert (Lambda, serverless)_\n* [Max Grigorev (forwidur)](https://github.com/forwidur) — _editor (EBS, RDS)_\n* [Jason Barry (JCBarry)](https://github.com/JCBarry) — [2+](https://github.com/open-guides/og-aws/commits?author=JCBarry)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3AJCBarry) — _editor (CloudWatch)_\n* [Kim Schmidt (kimschmidtsbrain)](https://github.com/kimschmidtsbrain) — [1+](https://github.com/open-guides/og-aws/commits?author=kimschmidtsbrain)/[4+](https://github.com/open-guides/og-aws/issues?q=author%3Akimschmidtsbrain) — _expert (AWS Marketplace, Aurora)_\n* [Manish Pandit (lobster1234)](https://github.com/lobster1234) — [15+](https://github.com/open-guides/og-aws/commits?author=lobster1234)/[14+](https://github.com/open-guides/og-aws/issues?q=author%3Alobster1234) — _editor (Batch, SQS, SNS)_\n* [Luke de Oliveira (lukedeo)](https://github.com/lukedeo) — [3+](https://github.com/open-guides/og-aws/commits?author=lukedeo)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Alukedeo) — _expert (machine learning, Terraform, orchestration)_\n* [Lynn Langit (lynnlangit)](https://github.com/lynnlangit) — [29+](https://github.com/open-guides/og-aws/commits?author=lynnlangit)/[26+](https://github.com/open-guides/og-aws/issues?q=author%3Alynnlangit) — _editor (IoT)_\n* [Max Zanko (max-zanko)](https://github.com/max-zanko) — [12+](https://github.com/open-guides/og-aws/commits?author=max-zanko)/[10+](https://github.com/open-guides/og-aws/issues?q=author%3Amax-zanko) — _editor (EC2, S3, Glacier, EMR, Redshift)_\n* [John Merrells (merrells)](https://github.com/merrells) — _expert (cloud infrastructure, when to use AWS)_\n* [Nitin S (nitingithub)](https://github.com/nitingithub) — [6+](https://github.com/open-guides/og-aws/commits?author=nitingithub)/[4+](https://github.com/open-guides/og-aws/issues?q=author%3Anitingithub) — _editor (cost management)_\n* [Noah Zoschke (nzoschke)](https://github.com/nzoschke) — [0+](https://github.com/open-guides/og-aws/commits?author=nzoschke)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Anzoschke) — _editor (KMS)_\n* [Rich Adams (richadams)](https://github.com/richadams) — [2+](https://github.com/open-guides/og-aws/commits?author=richadams)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Arichadams) — _editor (VPC)_\n* [Min (wumintendy)](https://github.com/wumintendy) — _expert (ECS, CloudWatch, SQS, RDS, WAF)_\n\n*Contributors*\n\n* [0xmohit](https://github.com/0xmohit) — [3+](https://github.com/open-guides/og-aws/commits?author=0xmohit)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3A0xmohit)\n* [Abdul Mohammed (abdulirfan3)](https://github.com/abdulirfan3) — [5+](https://github.com/open-guides/og-aws/commits?author=abdulirfan3)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Aabdulirfan3)\n* [AJ Kerrigan (ajkerrigan-mdsol)](https://github.com/ajkerrigan-mdsol) — [2+](https://github.com/open-guides/og-aws/commits?author=ajkerrigan-mdsol)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Aajkerrigan-mdsol)\n* [Alex Atallah (alexanderatallah)](https://github.com/alexanderatallah)\n* [Andre (andre-meireles)](https://github.com/andre-meireles) — [5+](https://github.com/open-guides/og-aws/commits?author=andre-meireles)/[6+](https://github.com/open-guides/og-aws/issues?q=author%3Aandre-meireles)\n* [Andrew Lane (AndrewLane)](https://github.com/AndrewLane) — [1+](https://github.com/open-guides/og-aws/commits?author=AndrewLane)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3AAndrewLane)\n* [Mattias (apelsinet)](https://github.com/apelsinet) — [0+](https://github.com/open-guides/og-aws/commits?author=apelsinet)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aapelsinet)\n* [Aron Woost (aronwoost)](https://github.com/aronwoost) — [0+](https://github.com/open-guides/og-aws/commits?author=aronwoost)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aaronwoost)\n* [Ahmed (Ashex)](https://github.com/Ashex) — [0+](https://github.com/open-guides/og-aws/commits?author=Ashex)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3AAshex)\n* [Simon Baynes (baynezy)](https://github.com/baynezy) — [2+](https://github.com/open-guides/og-aws/commits?author=baynezy)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3Abaynezy)\n* [Bo Bayles (bbayles)](https://github.com/bbayles) — [1+](https://github.com/open-guides/og-aws/commits?author=bbayles)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Abbayles)\n* [Benjamin Bunk (benbunk)](https://github.com/benbunk) — [1+](https://github.com/open-guides/og-aws/commits?author=benbunk)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Abenbunk)\n* [Alberto Hernandez (Beto2288)](https://github.com/Beto2288) — [2+](https://github.com/open-guides/og-aws/commits?author=Beto2288)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3ABeto2288)\n* [Adam Mathias Bittlingmayer (bittlingmayer)](https://github.com/bittlingmayer)\n* [Jesper Eneberg (Bizzelicious)](https://github.com/Bizzelicious) — [3+](https://github.com/open-guides/og-aws/commits?author=Bizzelicious)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3ABizzelicious)\n* [Bradly Feeley (bradly)](https://github.com/bradly) — [2+](https://github.com/open-guides/og-aws/commits?author=bradly)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Abradly)\n* [Brady Dowling (bradydowling)](https://github.com/bradydowling) — [1+](https://github.com/open-guides/og-aws/commits?author=bradydowling)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Abradydowling)\n* [Benjamin Wilson (brwilson)](https://github.com/brwilson) — [4+](https://github.com/open-guides/og-aws/commits?author=brwilson)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Abrwilson)\n* [Chris Eich (ceich)](https://github.com/ceich) — [0+](https://github.com/open-guides/og-aws/commits?author=ceich)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aceich)\n* [Joshua Buss (chicagobuss)](https://github.com/chicagobuss) — [0+](https://github.com/open-guides/og-aws/commits?author=chicagobuss)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Achicagobuss)\n* [Mårten Gustafson (chids)](https://github.com/chids) — [4+](https://github.com/open-guides/og-aws/commits?author=chids)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3Achids)\n* [Chris Griffin (chris-griffin)](https://github.com/chris-griffin) — [1+](https://github.com/open-guides/og-aws/commits?author=chris-griffin)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Achris-griffin)\n* [Chris Lennon (chrislennon)](https://github.com/chrislennon) — [1+](https://github.com/open-guides/og-aws/commits?author=chrislennon)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Achrislennon)\n* [Chris Leyva (chrisleyva)](https://github.com/chrisleyva) — [1+](https://github.com/open-guides/og-aws/commits?author=chrisleyva)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Achrisleyva)\n* [Rainer Eli (claushellsing)](https://github.com/claushellsing) — [1+](https://github.com/open-guides/og-aws/commits?author=claushellsing)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aclaushellsing)\n* [Tomasz Cholewa (cloudowski)](https://github.com/cloudowski) — [0+](https://github.com/open-guides/og-aws/commits?author=cloudowski)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Acloudowski)\n* [Joe Greene (ClydeMachine)](https://github.com/ClydeMachine) — [12+](https://github.com/open-guides/og-aws/commits?author=ClydeMachine)/[5+](https://github.com/open-guides/og-aws/issues?q=author%3AClydeMachine)\n* [Cristian Măgherușan-Stanciu @magheru_san (cristim)](https://github.com/cristim) — [2+](https://github.com/open-guides/og-aws/commits?author=cristim)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3Acristim)\n* [Matt Dalesio (dalmat36)](https://github.com/dalmat36) — [0+](https://github.com/open-guides/og-aws/commits?author=dalmat36)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Adalmat36)\n* [Dan Bower (danbower)](https://github.com/danbower) — [2+](https://github.com/open-guides/og-aws/commits?author=danbower)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Adanbower)\n* [Daniel Ehrlich (danielehrlich)](https://github.com/danielehrlich) — [3+](https://github.com/open-guides/og-aws/commits?author=danielehrlich)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3Adanielehrlich)\n* [Scott Francis (darkuncle)](https://github.com/darkuncle) — [0+](https://github.com/open-guides/og-aws/commits?author=darkuncle)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Adarkuncle)\n* [Daniel C. Daugherty (ddaugherty)](https://github.com/ddaugherty) — [0+](https://github.com/open-guides/og-aws/commits?author=ddaugherty)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Addaugherty)\n* [Chris Roe (dijitalmunky)](https://github.com/dijitalmunky) — [0+](https://github.com/open-guides/og-aws/commits?author=dijitalmunky)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Adijitalmunky)\n* [David Kavanagh (dkavanagh)](https://github.com/dkavanagh) — [3+](https://github.com/open-guides/og-aws/commits?author=dkavanagh)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Adkavanagh)\n* [David Kocher (dkocher)](https://github.com/dkocher) — [2+](https://github.com/open-guides/og-aws/commits?author=dkocher)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Adkocher)\n* [Dorrin (DorrinPk)](https://github.com/DorrinPk) — [5+](https://github.com/open-guides/og-aws/commits?author=DorrinPk)/[4+](https://github.com/open-guides/og-aws/issues?q=author%3ADorrinPk)\n* [Matthew Lapworth (dragonndev)](https://github.com/dragonndev) — [5+](https://github.com/open-guides/og-aws/commits?author=dragonndev)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Adragonndev)\n* [Dmitry Guyvoronsky (dreamiurg)](https://github.com/dreamiurg) — [1+](https://github.com/open-guides/og-aws/commits?author=dreamiurg)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Adreamiurg)\n* [Patrick McDavid (ehippy)](https://github.com/ehippy) — [1+](https://github.com/open-guides/og-aws/commits?author=ehippy)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aehippy)\n* [Elliott Spira (em0ney)](https://github.com/em0ney) — [5+](https://github.com/open-guides/og-aws/commits?author=em0ney)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3Aem0ney)\n* [Enis Özgen (enisozgen)](https://github.com/enisozgen) — [2+](https://github.com/open-guides/og-aws/commits?author=enisozgen)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Aenisozgen)\n* [esell (esell)](https://github.com/esell) — [5+](https://github.com/open-guides/og-aws/commits?author=esell)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aesell)\n* [gabinante](https://github.com/gabinante) — [0+](https://github.com/open-guides/og-aws/commits?author=gabinante)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Agabinante)\n* [Brad Campbell (geekmuse)](https://github.com/geekmuse) — [6+](https://github.com/open-guides/og-aws/commits?author=geekmuse)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3Ageekmuse)\n* [Greg Leeds (gleeds)](https://github.com/gleeds) — [2+](https://github.com/open-guides/og-aws/commits?author=gleeds)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Agleeds)\n* [Glynn Forrest (glynnforrest)](https://github.com/glynnforrest) — [1+](https://github.com/open-guides/og-aws/commits?author=glynnforrest)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aglynnforrest)\n* [Dmitry Golyshev (golyshev)](https://github.com/golyshev)\n* [gscalise](https://github.com/gscalise) — [1+](https://github.com/open-guides/og-aws/commits?author=gscalise)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Agscalise)\n* [Gulam Shakir (gshakir)](https://github.com/gshakir) — [2+](https://github.com/open-guides/og-aws/commits?author=gshakir)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Agshakir)\n* [Ben Hecht (hb3b)](https://github.com/hb3b) — [0+](https://github.com/open-guides/og-aws/commits?author=hb3b)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Ahb3b)\n* [Hendrik Richter (hendi)](https://github.com/hendi) — [2+](https://github.com/open-guides/og-aws/commits?author=hendi)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Ahendi)\n* [hortau-ci](https://github.com/hortau-ci)\n* [Theo Hultberg (iconara)](https://github.com/iconara) — [1+](https://github.com/open-guides/og-aws/commits?author=iconara)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aiconara)\n* [Ben Bridts (ikben)](https://github.com/ikben) — [2+](https://github.com/open-guides/og-aws/commits?author=ikben)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Aikben)\n* [Dan O'Brien (InTheCloudDan)](https://github.com/InTheCloudDan) — [2+](https://github.com/open-guides/og-aws/commits?author=InTheCloudDan)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3AInTheCloudDan)\n* [Itay Shakury (itaysk)](https://github.com/itaysk) — [1+](https://github.com/open-guides/og-aws/commits?author=itaysk)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Aitaysk)\n* [Jose Luis Ordiales Coscia (jlordiales)](https://github.com/jlordiales) — [1+](https://github.com/open-guides/og-aws/commits?author=jlordiales)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Ajlordiales)\n* [Jaanus Torp (jnsaff)](https://github.com/jnsaff) — [1+](https://github.com/open-guides/og-aws/commits?author=jnsaff)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Ajnsaff)\n* [Jason Poley (jpoley)](https://github.com/jpoley) — [0+](https://github.com/open-guides/og-aws/commits?author=jpoley)/[4+](https://github.com/open-guides/og-aws/issues?q=author%3Ajpoley)\n* [Julien Duchesne (julienduchesne)](https://github.com/julienduchesne) — [2+](https://github.com/open-guides/og-aws/commits?author=julienduchesne)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3Ajulienduchesne)\n* Jurgen Philippaerts\n* [KAZUYUKI TANIMURA (kazuyukitanimura)](https://github.com/kazuyukitanimura) — [3+](https://github.com/open-guides/og-aws/commits?author=kazuyukitanimura)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Akazuyukitanimura)\n* [Kyle Busekist (kbusekist)](https://github.com/kbusekist) — [2+](https://github.com/open-guides/og-aws/commits?author=kbusekist)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Akbusekist)\n* [David Kosslyn (kozzles)](https://github.com/kozzles) — [0+](https://github.com/open-guides/og-aws/commits?author=kozzles)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Akozzles)\n* [Karthik Prabhakar (kprabhak)](https://github.com/kprabhak) — [2+](https://github.com/open-guides/og-aws/commits?author=kprabhak)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Akprabhak)\n* [Krishan Bhasin (KrishanBhasin)](https://github.com/KrishanBhasin) — [3+](https://github.com/open-guides/og-aws/commits?author=KrishanBhasin)/[5+](https://github.com/open-guides/og-aws/issues?q=author%3AKrishanBhasin)\n* [Laurent Jalbert-Simard (laurrentt)](https://github.com/laurrentt) — [0+](https://github.com/open-guides/og-aws/commits?author=laurrentt)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Alaurrentt)\n* [Łukasz Kostka (luqasz)](https://github.com/luqasz) — [4+](https://github.com/open-guides/og-aws/commits?author=luqasz)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aluqasz)\n* [maiki](https://github.com/maiki) — [1+](https://github.com/open-guides/og-aws/commits?author=maiki)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Amaiki)\n* [Manoj M J (manojmj92)](https://github.com/manojmj92) — [1+](https://github.com/open-guides/og-aws/commits?author=manojmj92)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Amanojmj92)\n* [Marcello Bastéa-Forte (marcello3d)](https://github.com/marcello3d)\n* [Martijn Dwars (MartijnDwars)](https://github.com/MartijnDwars) — [3+](https://github.com/open-guides/og-aws/commits?author=MartijnDwars)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3AMartijnDwars)\n* [Matthias Rampke (matthiasr)](https://github.com/matthiasr) — [2+](https://github.com/open-guides/og-aws/commits?author=matthiasr)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Amatthiasr)\n* [Michael Pereira (MichaelPereira)](https://github.com/MichaelPereira) — [0+](https://github.com/open-guides/og-aws/commits?author=MichaelPereira)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3AMichaelPereira)\n* [Mikael Finstad (mifi)](https://github.com/mifi) — [0+](https://github.com/open-guides/og-aws/commits?author=mifi)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Amifi)\n* [Mike  (mikejennings)](https://github.com/mikejennings) — [0+](https://github.com/open-guides/og-aws/commits?author=mikejennings)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Amikejennings)\n* [Mikhail Advani (mikhailadvani)](https://github.com/mikhailadvani) — [5+](https://github.com/open-guides/og-aws/commits?author=mikhailadvani)/[5+](https://github.com/open-guides/og-aws/issues?q=author%3Amikhailadvani)\n* [Magnus Kulke (mkulke)](https://github.com/mkulke) — [4+](https://github.com/open-guides/og-aws/commits?author=mkulke)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3Amkulke)\n* [Mike Mattice (mmattice)](https://github.com/mmattice) — [0+](https://github.com/open-guides/og-aws/commits?author=mmattice)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Ammattice)\n* [Michael Petychakis (mpetyx)](https://github.com/mpetyx) — [2+](https://github.com/open-guides/og-aws/commits?author=mpetyx)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Ampetyx)\n* [Mathias Leppich (muhqu)](https://github.com/muhqu) — [3+](https://github.com/open-guides/og-aws/commits?author=muhqu)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Amuhqu)\n* [Neil Bostrom (NeilBostrom)](https://github.com/NeilBostrom) — [0+](https://github.com/open-guides/og-aws/commits?author=NeilBostrom)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3ANeilBostrom)\n* [Justin Mullis (neontuna)](https://github.com/neontuna) — [1+](https://github.com/open-guides/og-aws/commits?author=neontuna)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aneontuna)\n* [Mark Tse (neverendingqs)](https://github.com/neverendingqs) — [0+](https://github.com/open-guides/og-aws/commits?author=neverendingqs)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aneverendingqs)\n* [nickbarclay](https://github.com/nickbarclay) — [2+](https://github.com/open-guides/og-aws/commits?author=nickbarclay)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Anickbarclay)\n* [Nik Nyby (nikolas)](https://github.com/nikolas) — [0+](https://github.com/open-guides/og-aws/commits?author=nikolas)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Anikolas)\n* [Ola Wiberg (olawiberg)](https://github.com/olawiberg)\n* [Pascal Borreli (pborreli)](https://github.com/pborreli) — [1+](https://github.com/open-guides/og-aws/commits?author=pborreli)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Apborreli)\n* [Piotr Grzesik (pgrzesik)](https://github.com/pgrzesik) — [2+](https://github.com/open-guides/og-aws/commits?author=pgrzesik)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3Apgrzesik)\n* [Phillip Calvin (pnc)](https://github.com/pnc) — [1+](https://github.com/open-guides/og-aws/commits?author=pnc)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Apnc)\n* Praveen Patnala\n* [Raajhesh Kannaa Chidambaram (raajheshkannaa)](https://github.com/raajheshkannaa) — [1+](https://github.com/open-guides/og-aws/commits?author=raajheshkannaa)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Araajheshkannaa)\n* [Ram Nadella (ram-nadella)](https://github.com/ram-nadella) — [1+](https://github.com/open-guides/og-aws/commits?author=ram-nadella)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Aram-nadella)\n* [Raphaël Riel (raphael-riel)](https://github.com/raphael-riel) — [0+](https://github.com/open-guides/og-aws/commits?author=raphael-riel)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Araphael-riel)\n* [Richard Birkby (rbirkby)](https://github.com/rbirkby) — [2+](https://github.com/open-guides/og-aws/commits?author=rbirkby)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Arbirkby)\n* [Federico Hernandez (recollir)](https://github.com/recollir) — [1+](https://github.com/open-guides/og-aws/commits?author=recollir)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Arecollir)\n* [Ric Harvey (richarvey)](https://github.com/richarvey) — [0+](https://github.com/open-guides/og-aws/commits?author=richarvey)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aricharvey)\n* [Rich Hintz (rjhintz)](https://github.com/rjhintz) — [11+](https://github.com/open-guides/og-aws/commits?author=rjhintz)/[14+](https://github.com/open-guides/og-aws/issues?q=author%3Arjhintz)\n* [Russell Power (rjpower)](https://github.com/rjpower)\n* [Ryan Green (rpgreen)](https://github.com/rpgreen) — [0+](https://github.com/open-guides/og-aws/commits?author=rpgreen)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Arpgreen)\n* [Russell Davies (russelldavies)](https://github.com/russelldavies) — [0+](https://github.com/open-guides/og-aws/commits?author=russelldavies)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Arusselldavies)\n* [Ryan Guest (ryanguest)](https://github.com/ryanguest) — [0+](https://github.com/open-guides/og-aws/commits?author=ryanguest)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aryanguest)\n* [Ryan Park (RyanGWU82)](https://github.com/RyanGWU82) — [2+](https://github.com/open-guides/og-aws/commits?author=RyanGWU82)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3ARyanGWU82)\n* [Ryan Brown (ryansb)](https://github.com/ryansb) — [0+](https://github.com/open-guides/og-aws/commits?author=ryansb)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aryansb)\n* [David Schott (schottsfired)](https://github.com/schottsfired) — [1+](https://github.com/open-guides/og-aws/commits?author=schottsfired)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aschottsfired)\n* [Ashley Davis (SgtCoDFish)](https://github.com/SgtCoDFish) — [1+](https://github.com/open-guides/og-aws/commits?author=SgtCoDFish)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3ASgtCoDFish)\n* [Kushan Shah (shahkushan1)](https://github.com/shahkushan1) — [0+](https://github.com/open-guides/og-aws/commits?author=shahkushan1)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Ashahkushan1)\n* [Simon Taft (shtaft)](https://github.com/shtaft) — [0+](https://github.com/open-guides/og-aws/commits?author=shtaft)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Ashtaft)\n* [Shubham Aggarwal (shubham391)](https://github.com/shubham391) — [1+](https://github.com/open-guides/og-aws/commits?author=shubham391)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Ashubham391)\n* [Alessio \"LeX\" Calafiore (sohlex)](https://github.com/sohlex) — [0+](https://github.com/open-guides/og-aws/commits?author=sohlex)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Asohlex)\n* [Seth Rutner (sprutner)](https://github.com/sprutner) — [0+](https://github.com/open-guides/og-aws/commits?author=sprutner)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Asprutner)\n* [Adam Nelson (spudstuff)](https://github.com/spudstuff) — [4+](https://github.com/open-guides/og-aws/commits?author=spudstuff)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Aspudstuff)\n* [Stanley Zheng (stanzheng)](https://github.com/stanzheng) — [0+](https://github.com/open-guides/og-aws/commits?author=stanzheng)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Astanzheng)\n* [Steven Maude (StevenMaude)](https://github.com/StevenMaude) — [1+](https://github.com/open-guides/og-aws/commits?author=StevenMaude)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3AStevenMaude)\n* [Suny Kim (sunygit)](https://github.com/sunygit) — [0+](https://github.com/open-guides/og-aws/commits?author=sunygit)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Asunygit)\n* [Carlos (theist)](https://github.com/theist) — [1+](https://github.com/open-guides/og-aws/commits?author=theist)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Atheist)\n* [TheRandomSecurityGuy (therandomsecurityguy)](https://github.com/therandomsecurityguy) — [1+](https://github.com/open-guides/og-aws/commits?author=therandomsecurityguy)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Atherandomsecurityguy)\n* [Sandeep Dinesh (thesandlord)](https://github.com/thesandlord) — [1+](https://github.com/open-guides/og-aws/commits?author=thesandlord)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Athesandlord)\n* [Thibault Charbonnier (thibaultcha)](https://github.com/thibaultcha) — [3+](https://github.com/open-guides/og-aws/commits?author=thibaultcha)/[3+](https://github.com/open-guides/og-aws/issues?q=author%3Athibaultcha)\n* [thomas michael wallace (thomasmichaelwallace)](https://github.com/thomasmichaelwallace) — [0+](https://github.com/open-guides/og-aws/commits?author=thomasmichaelwallace)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Athomasmichaelwallace)\n* [Tom Schlick (tomschlick)](https://github.com/tomschlick) — [3+](https://github.com/open-guides/og-aws/commits?author=tomschlick)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Atomschlick)\n* [Trayton White (traytonwhite)](https://github.com/traytonwhite) — [1+](https://github.com/open-guides/og-aws/commits?author=traytonwhite)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Atraytonwhite)\n* [robo-mo (ukanth)](https://github.com/ukanth) — [0+](https://github.com/open-guides/og-aws/commits?author=ukanth)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Aukanth)\n* [Uli Stroetz (ustroetz)](https://github.com/ustroetz) — [1+](https://github.com/open-guides/og-aws/commits?author=ustroetz)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Austroetz)\n* [Victor Avasiloaei (victorelu)](https://github.com/victorelu) — [0+](https://github.com/open-guides/og-aws/commits?author=victorelu)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Avictorelu)\n* [Vincent (vincent-dm)](https://github.com/vincent-dm) — [1+](https://github.com/open-guides/og-aws/commits?author=vincent-dm)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Avincent-dm)\n* [Andy (virtualandy)](https://github.com/virtualandy) — [0+](https://github.com/open-guides/og-aws/commits?author=virtualandy)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Avirtualandy)\n* [Walter King (walterking)](https://github.com/walterking) — [0+](https://github.com/open-guides/og-aws/commits?author=walterking)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Awalterking)\n* [Costa Michailidis (wamoyo)](https://github.com/wamoyo) — [1+](https://github.com/open-guides/og-aws/commits?author=wamoyo)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Awamoyo)\n* [Stefan Zier (weirded)](https://github.com/weirded)\n* [Michael Ortali (xethorn)](https://github.com/xethorn) — [1+](https://github.com/open-guides/og-aws/commits?author=xethorn)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Axethorn)\n* [Rob Smart (zekizeki)](https://github.com/zekizeki) — [0+](https://github.com/open-guides/og-aws/commits?author=zekizeki)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Azekizeki)\n* [Jifeng Zhang (zjfroot)](https://github.com/zjfroot) — [1+](https://github.com/open-guides/og-aws/commits?author=zjfroot)/[1+](https://github.com/open-guides/og-aws/issues?q=author%3Azjfroot)\n* [Andreas Zoellner (zoellner)](https://github.com/zoellner) — [2+](https://github.com/open-guides/og-aws/commits?author=zoellner)/[2+](https://github.com/open-guides/og-aws/issues?q=author%3Azoellner)\n\nContributors are listed alphabetically with assigned roles first.\nPlease don't PR the AUTHORS.md or authors-info.yml files! It is auto-generated regularly by the project leads.\nPlease let the project leads know of any errors or omissions on this list.\n\n\n\n(This file was auto-generated by [ghizmo assemble-authors](https://github.com/jlevy/ghizmo).)"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment include:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or advances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at og-aws@lexikon.io. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]\n\n[homepage]: http://contributor-covenant.org\n[version]: http://contributor-covenant.org/version/1/4/\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "Contributing\n------------\n\n[![Slack Chat](https://img.shields.io/badge/Chat-Slack-ff69b4.svg \"Join us. Anyone is welcome!\")](https://og-aws-slack.lexikon.io/)\n\nContributions of all kinds, including discussion, corrections, additions, and improvements, are welcome! We hope you'll join and help, in small ways or large. We gladly [credit](/AUTHORS.md) all contributors. Here are few notes before you jump in.\n\nPlease Help\n-----------\n\nIf you’ve found this guide useful, please see if you can help (in increasing levels of commitment and expertise):\n\n-\t**Discussion:** The easiest thing you can do to contribute is [**join the Slack channel**](https://og-aws-slack.lexikon.io/) and ask or answer questions. As we discuss, see if it points to new things you or others can contribute to the Guide.\nhelps the community and guides what contributors can focus on.\n-\t**Focused pull requests:** [Pull requests](https://github.com/open-guides/og-aws/pulls) with focused changes like typos, specific tips, and corrections are always welcome and fast to review and merge in. Keep them small and focused, and *use multiple PRs for unrelated changes*. (See [writing conventions](#writing-conventions) below.)\n-\t**Track issues:** [File issues](https://github.com/open-guides/og-aws/issues) to aggregate ideas or links if it’s clear something needs to be improved, but it’s not possible to file a PR immediately.\n-\t**Major pull requests:** Take a look at areas [where we need help](https://github.com/open-guides/og-aws/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22). If you want to make a larger change, such as rewriting a lot of content, changing style, or adding a section, discussion in Slack is helpful and usually necessary. For new additions, we often create and edit the first draft in [Quip](https://quip.com/).\n-\t**Deeper expertise:** If you have deep expertise, let one of the project leads know if you’re interested in being an **editor** or an **expert**. Editors and experts are assigned roles that [help us review](#editorial-process) the Guide.\n\nReview Process\n--------------\n\n### Pull Request Etiquette\n\n-\tKeep changes as small as is practical. Do not make changes to multiple sections at once, alter whitespace in broad ways, etc.\n-\t**Neutrality:** If you have an affiliation related to what you are changing, please mention it.\n-\tPlease do your best to review current issues and pull requests to avoid duplication.\n\n### Writing Style\n\n-\t**Link to references:** If you are adding an item, whenever possible, try to add a link or reference to relevant discussion or reference pages.\n-\t**Be brief:** Avoid long expository paragraphs; it’s better to link to a blog. (We are open to linking to your own blog, if it’s the best source.)\n-\t**Include opinions and common practice:** Thoughtful opinion is helpful. If there are multiple conventions or ideas on something held by experts, mention the different ones.\n-\t**Clarity:** Strive for consistency with conventions listed here, but clarity is most important.\n\n### Pull Request Review\n\nWhen creating a PR or reviewing one, it’s helpful to consider a few questions:\n\n1.\tAre relevant docs linked (AWS and third party blogs)?\n2.\tCan more details be added without lengthening it significantly?\n3.\tCan the same information be conveyed with more succinctly or more clearly?\n4.\tCopy editing: Does it match the [writing style](#writing-style) and [conventions](#writing-conventions) (including emoji symbols, punctuation, and grammar)?\n5.\tAre there any other parts of the guide that should be updated at the same time? (Examples are adding new sections to the table of contents, adding new internal links, rows to tables, etc.)\n6.\tAre there additional improvements that should be filed as issues?\n\n### Editorial Process\n\n-\tRoles:\n\t-\t**Project leads:** Own overall quality of the Guide, direction, and process.\n\t-\t**Editors:** Contributors own specific sections or aspects of the Guide, reviewing PRs and/or writing. Requires expert knowledge.\n\t-\t**Experts:** People with expert knowledge in various areas, who assist editors and have agreed to review or help on demand with tougher questions or PRs.\n\t-\t**Contributors:** Everyone who contributes content or helps one way or another.\n-\tAll PRs are reviewed by an **editor** and for non-trivial changes, a **project lead**, usually in that order, but it can be reversed for expediency.\n-\tIn addition, anyone with relevant knowledge is encouraged to review/comment on PRs.\n-\tBoth editors and project leads are responsible for checking for style or problems.\n-\tTrivial changes (including copy editing) may be merged in directly by project leads or editors.\n\nWriting Conventions\n-------------------\n\nTo keep a polished, consistent style we list a bunch of our conventions. Try to follow these and/or enforce them in reviews:\n\n-\t**Abbreviations:** For AWS service names, we use the abbreviation throughout the guide if it is more common, e.g. EC2 and not Elastic Compute Cloud. We also omit “Amazon” at the front of product names, e.g. EMR and not Amazon EMR. If an abbreviation is convenient but not always used, e.g. AZ instead of Availability Zone, either use the full term once per section/paragraph and abbreviate subsequent usages or do not abbreviate it at all.\n-\tTerms that appear for the first time in **boldface** are defined there in a brief summary, with a link if possible to what is probably the best page for that concept. It’s also fine to boldface **key statements** that guide the eye.\n-\t**Boldfaced headings:** When possible and appropriate, begin bulleted items with a boldfaced summary, as illustrated here. This helps the reader skim the contents.\n-\t**Links:**\n\t-\tRelated content that elaborates or gives more detail is included via standard inline hyperlinks within the text.\n\t-\tReferences or citations backing some info that is already explained in the text is in [brackets] at the end of the item (with link for web pages, no link for books).\n-\t**Emoji icons:** These icons aid readability; use them whenever appropriate (usually at the start of bulleted items), as listed in the [**legend**](https://github.com/open-guides/og-aws#legend).\n-\t**Typographical conventions:**\n\t-\tUse Unicode open and close quotes “like this” and not \"like this\".\n\t-\tUse oriented apostrophes (Unicode’s, not ASCII's).\n\t-\tUse em dashes — like this (not two hyphens -- like this).\n-\t**Section conventions:** When appropriate please add sections covering these items (where *X* = EC2, S3, etc.):\n\t-\t*X Basics*: The elementary facts you should know if you don’t yet know anything about the service.\n\t-\t*X Alternatives and Lock-In*: Should you be using this service or something else? Is the decision an important one that locks you in?\n\t-\t*X Tips*: Everything you should know about the service, from big stuff to details.\n\t-\t*X Gotchas and Limitations*: Common problems, large and small, as well as misconceptions and quirks.\n\t-\tNot all sections need to follow the above conventions exactly.\n\t-\tNote we try to make sections uniquely titled, so GitHub links to Markdown section anchors don’t collide and are stable.\n\nOccasionally, we keep consistent formatting in Markdown via [markdownfmt](https://github.com/shurcooL/markdownfmt). (One of the project leads might run **admin/reformat.sh** to do this, but you can safely ignore that.)\n\nContact\n-------\n\nIf you have concerns or additional ideas of ways to help, e-mail **og-aws@lexikon.io** or use Slack to contact the [project leads](AUTHORS.md).\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "Attribution 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an \"as-is\" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n     Considerations for licensors: Our public licenses are\n     intended for use by those authorized to give the public\n     permission to use material in ways otherwise restricted by\n     copyright and certain other rights. Our licenses are\n     irrevocable. Licensors should read and understand the terms\n     and conditions of the license they choose before applying it.\n     Licensors should also secure all rights necessary before\n     applying our licenses so that the public can reuse the\n     material as expected. Licensors should clearly mark any\n     material not subject to the license. This includes other CC-\n     licensed material, or material used under an exception or\n     limitation to copyright. More considerations for licensors:\n\twiki.creativecommons.org/Considerations_for_licensors\n\n     Considerations for the public: By using one of our public\n     licenses, a licensor grants the public permission to use the\n     licensed material under specified terms and conditions. If\n     the licensor's permission is not necessary for any reason--for\n     example, because of any applicable exception or limitation to\n     copyright--then that use is not regulated by the license. Our\n     licenses grant only permissions under copyright and certain\n     other rights that a licensor has authority to grant. Use of\n     the licensed material may still be restricted for other\n     reasons, including because others have copyright or other\n     rights in the material. A licensor may make special requests,\n     such as asking that all changes be marked or described.\n     Although not required by our licenses, you are encouraged to\n     respect those requests where reasonable. More_considerations\n     for the public:\n\twiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution 4.0 International Public License\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution 4.0 International Public License (\"Public License\"). To the\nextent this Public License may be interpreted as a contract, You are\ngranted the Licensed Rights in consideration of Your acceptance of\nthese terms and conditions, and the Licensor grants You such rights in\nconsideration of benefits the Licensor receives from making the\nLicensed Material available under these terms and conditions.\n\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n\n  d. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  e. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  f. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  g. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  h. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  i. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  j. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  k. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part; and\n\n            b. produce, reproduce, and Share Adapted Material.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties.\n\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n       4. If You Share Adapted Material You produce, the Adapter's\n          License You apply must not prevent recipients of the Adapted\n          Material from complying with this Public License.\n\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material; and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n\n=======================================================================\n\nCreative Commons is not a party to its public\nlicenses. Notwithstanding, Creative Commons may elect to apply one of\nits public licenses to material it publishes and in those instances\nwill be considered the “Licensor.” The text of the Creative Commons\npublic licenses is dedicated to the public domain under the CC0 Public\nDomain Dedication. Except for the limited purpose of indicating that\nmaterial is shared under a Creative Commons public license or as\notherwise permitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the\npublic licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n"
  },
  {
    "path": "README.md",
    "content": "![An Open Guide](figures/signpost-horiz1-1600.jpg)\n\nThe Open Guide to Amazon Web Services\n=====================================\n\n[![Slack Chat](https://img.shields.io/badge/Chat-Slack-ff69b4.svg \"Join us. Anyone is welcome!\")](http://slackhatesthe.cloud) ⇦ Join us!\n\n[Credits](AUTHORS.md) ∙ [Contributing guidelines](CONTRIBUTING.md)\n\nTable of Contents\n-----------------\n\n**Purpose**\n\n-\t[Why an Open Guide?](#why-an-open-guide)\n-\t[Scope](#scope)\n-\t[Legend](#legend)\n\n**AWS in General**\n\n-\t[General Information](#general-information)\n-\t[Learning and Career Development](#learning-and-career-development)\n-\t[Managing AWS](#managing-aws)\n-\t[Managing Servers and Applications](#managing-servers-and-applications)\n\n| Specific AWS Services                 | Basics                         | Tips                          | Gotchas                                        |\n|---------------------------------------|--------------------------------|-------------------------------|------------------------------------------------|\n| [ALB](#alb) | [📗](#alb-basics) | [📘](#alb-tips) | [📙](#alb-gotchas-and-limitations) |\n| [AMIs](#amis) | [📗](#ami-basics) | [📘](#ami-tips) | [📙](#ami-gotchas-and-limitations) |\n| [API Gateway](#api-gateway) | [📗](#api-gateway-basics) | [📘](#api-gateway-tips) | [📙](#api-gateway-gotchas-and-limitations) |\n| [Auto Scaling](#auto-scaling) | [📗](#auto-scaling-basics) | [📘](#auto-scaling-tips) | [📙](#auto-scaling-gotchas-and-limitations) |\n| [Batch](#batch) | [📗](#batch-basics) | [📘](#batch-tips) |\n| [Certificate Manager](#certificate-manager) | [📗](#certificate-manager-basics) | [📘](#certificate-manager-tips) | [📙](#certificate-manager-gotchas-and-limitations) |\n| [CLB (ELB)](#clb) | [📗](#clb-basics) | [📘](#clb-tips) | [📙](#clb-gotchas-and-limitations) |\n| [CloudFront](#cloudfront) | [📗](#cloudfront-basics) | [📘](#cloudfront-tips) | [📙](#cloudfront-gotchas-and-limitations) |\n| [CloudFormation](#cloudformation) | [📗](#cloudformation-basics) | [📘](#cloudformation-tips) | [📙](#cloudformation-gotchas-and-limitations) |\n| [CloudWatch](#cloudwatch) | [📗](#cloudwatch-basics) | [📘](#cloudwatch-tips) | [📙](#cloudwatch-gotchas-and-limitations) |\n| [Device Farm](#device-farm) | [📗](#device-farm-basics) | [📘](#device-farm-tips) | [📙](#device-farm-gotchas-and-limitations) |\n| [DirectConnect](#directconnect) | [📗](#directconnect-basics) | [📘](#directconnect-tips) |  |\n| [DynamoDB](#dynamodb) | [📗](#dynamodb-basics) | [📘](#dynamodb-tips) | [📙](#dynamodb-gotchas-and-limitations) |\n| [EBS](#ebs) | [📗](#ebs-basics) | [📘](#ebs-tips) | [📙](#ebs-gotchas-and-limitations) |\n| [EC2](#ec2) | [📗](#ec2-basics) | [📘](#ec2-tips) | [📙](#ec2-gotchas-and-limitations) |\n| [ECS](#ecs) | [📗](#ecs-basics) | [📘](#ecs-tips) |  |\n| [EKS](#eks) | [📗](#eks-basics) | [📘](#eks-tips) | [📙](#eks-gotchas-and-limitations)  |\n| [EFS](#efs) | [📗](#efs-basics) | [📘](#efs-tips) | [📙](#efs-gotchas-and-limitations) |\n| [Elastic Beanstalk](#elastic-beanstalk) | [📗](#elastic-beanstalk-basics) | [📘](#elastic-beanstalk-tips) | [📙](#elastic-beanstalk-gotchas-and-limitations) |\n| [Elastic IPs](#elastic-ips) | [📗](#elastic-ip-basics) | [📘](#elastic-ip-tips) | [📙](#elastic-ip-gotchas-and-limitations) |\n| [ElastiCache](#elasticache) | [📗](#elasticache-basics) | [📘](#elasticache-tips) | [📙](#elasticache-gotchas-and-limitations) |\n| [EMR](#emr) | [📗](#emr-basics) | [📘](#emr-tips) | [📙](#emr-gotchas-and-limitations) |\n| [Fargate](#fargate) | [📗](#fargate-basics) | [📘](#fargate-tips) | [📙](#fargate-gotchas-and-limitations) |\n| [Glacier](#glacier) | [📗](#glacier-basics) | [📘](#glacier-tips) | [📙](#glacier-gotchas-and-limitations) |\n| [IoT](#iot) | [📗](#iot-basics) | [📘](#iot-tips) | [📙](#iot-gotchas-and-limitations) |\n| [Kinesis Firehose](#kinesis-firehose) |  |  | [📙](#kinesis-firehose-gotchas-and-limitations) |\n| [Kinesis Streams](#kinesis-streams) | [📗](#kinesis-streams-basics) | [📘](#kinesis-streams-tips) | [📙](#kinesis-streams-gotchas-and-limitations) |\n| [KMS](#kms) | [📗](#kms-basics) | [📘](#kms-tips) | [📙](#kms-gotchas-and-limitations) |\n| [Lambda](#lambda) | [📗](#lambda-basics) | [📘](#lambda-tips) | [📙](#lambda-gotchas-and-limitations) |\n| [Load Balancers](#load-balancers) | [📗](#load-balancer-basics) | [📘](#load-balancer-tips) | [📙](#load-balancer-gotchas-and-limitations) |\n| [Mobile Hub](#mobile-hub) | [📗](#mobile-hub-basics) | [📘](#mobile-hub-tips) | [📙](#mobile-hub-gotchas-and-limitations) |\n| [OpsWorks](#opsworks) | [📗](#opsworks-basics) | [📘](#opsworks-tips) | [📙](#opsworks-gotchas-and-limitations) |\n| [Quicksight](#quicksight) | [📗](#quicksight-basics) | | [📙](#quicksight-gotchas-and-limitations) |\n| [RDS](#rds) | [📗](#rds-basics) | [📘](#rds-tips) | [📙](#rds-gotchas-and-limitations) |\n| [RDS Aurora](#rds-aurora) | [📗](#rds-aurora-basics) | [📘](#rds-aurora-tips) | [📙](#rds-aurora-gotchas-and-limitations) |\n| [RDS Aurora MySQL](#rds-aurora-mysql) | [📗](#rds-aurora-mysql-basics) | [📘](#rds-aurora-mysql-tips) | [📙](#rds-aurora-mysql-gotchas-and-limitations) |\n| [RDS Aurora PostgreSQL](#rds-aurora-postgresql) | [📗](#rds-aurora-postgresql-basics) | [📘](#rds-aurora-postgresql-tips) | [📙](#rds-aurora-postgresql-gotchas-and-limitations) |\n| [RDS MySQL and MariaDB](#rds-mysql-and-mariadb) | [📗](#rds-mysql-and-mariadb-basics) | [📘](#rds-mysql-and-mariadb-tips) | [📙](#rds-mysql-and-mariadb-gotchas-and-limitations) |\n| [RDS PostgreSQL](#rds-postgresql) | [📗](#rds-postgresql-basics) | [📘](#rds-postgresql-tips) | [📙](#rds-postgresql-gotchas-and-limitations) |\n| [RDS SQL Server](#rds-sql-server) | [📗](#rds-sql-server-basics) | [📘](#rds-sql-server-tips) | [📙](#rds-sql-server-gotchas-and-limitations) |\n| [Redshift](#redshift) | [📗](#redshift-basics) | [📘](#redshift-tips) | [📙](#redshift-gotchas-and-limitations) |\n| [Route 53](#route-53) | [📗](#route-53-basics) | [📘](#route-53-tips) | [📙](#route-53-gotchas-and-limitations) |\n| [S3](#s3) | [📗](#s3-basics) | [📘](#s3-tips) | [📙](#s3-gotchas-and-limitations) |\n| [Security and IAM](#security-and-iam) | [📗](#security-and-iam-basics) | [📘](#security-and-iam-tips) | [📙](#security-and-iam-gotchas-and-limitations) |\n| [SES](#ses) | [📗](#ses-basics) | [📘](#ses-tips) | [📙](#ses-gotchas-and-limitations) |\n| [SNS](#sns) | [📗](#sns-basics) | [📘](#sns-tips) | [📙](#sns-gotchas-and-limitations) |\n| [SQS](#sqs) | [📗](#sqs-basics) | [📘](#sqs-tips) | [📙](#sqs-gotchas-and-limitations) |\n| [Step Functions](#step-functions) | [📗](#step-functions-basics) | [📘](#step-functions-tips) | [📙](#step-functions-gotchas-and-limitations) |\n| [WAF](#waf) | [📗](#waf-basics) | [📘](#waf-tips) | [📙](#waf-gotchas-and-limitations) |\n| [VPCs, Network Security, and Security Groups](#vpcs-network-security-and-security-groups) | [📗](#vpc-basics) | [📘](#vpc-and-network-security-tips) | [📙](#vpc-and-network-security-gotchas-and-limitations) |\n\n**Special Topics**\n\n-\t[High Availability](#high-availability)\n-\t[Billing and Cost Management](#billing-and-cost-management)\n-\t[Further Reading](#further-reading)\n\n**Legal**\n\n-\t[Disclaimer](#disclaimer)\n-\t[License](#license)\n\n**Figures and Tables**\n\n[![Tools and Services Market Landscape](figures/aws-market-landscape-320px.png)](#tools-and-services-market-landscape) [![AWS Data Transfer Costs](figures/aws-data-transfer-costs-320px.png)](#aws-data-transfer-costs)\n\n-\t[Figure: Tools and Services Market Landscape](#tools-and-services-market-landscape): A selection of third-party companies/products\n-\t[Figure: AWS Data Transfer Costs](#aws-data-transfer-costs): Visual overview of data transfer costs\n-\t[Table: Service Matrix](#service-matrix): How AWS services compare to alternatives\n-\t[Table: AWS Product Maturity and Releases](#aws-product-maturity-and-releases): AWS product releases\n-\t[Table: Storage Durability, Availability, and Price](#storage-durability-availability-and-price): A quantitative comparison\n\nWhy an Open Guide?\n------------------\n\nA lot of information on AWS is already written. Most people learn AWS by reading a blog or a “[getting started guide](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html)” and referring to the [standard AWS references](https://aws.amazon.com/documentation/). Nonetheless, trustworthy and practical information and recommendations aren’t easy to come by. AWS’s own documentation is a great but sprawling resource few have time to read fully, and it doesn’t include anything but official facts, so omits experiences of engineers. The information in blogs or [Stack Overflow](http://stackoverflow.com/questions/tagged/amazon-web-services) is also not consistently up to date.\n\nThis guide is by and for engineers who use AWS. It aims to be a useful, living reference that consolidates links, tips, gotchas, and best practices. It arose from discussion and editing over beers by [several engineers](AUTHORS.md) who have used AWS extensively.\n\nBefore using the guide, please read the [**license**](#license) and [**disclaimer**](#disclaimer).\n\n[Back to top :arrow_up:](#table-of-contents)\n### Please help!\n\n**This is an early in-progress draft!** It’s our first attempt at assembling this information, so is far from comprehensive still, and likely to have omissions or errors.\n\n[![Slack Chat](https://img.shields.io/badge/Chat-Slack-ff69b4.svg \"Join us. Anyone is welcome!\")](http://slackhatesthe.cloud)\n\nPlease help by [**joining the Slack channel**](http://slackhatesthe.cloud) (we like to talk about AWS in general, even if you only have questions — discussion helps the community and guides improvements) and [**contributing to the guide**](CONTRIBUTING.md). This guide is *open to contributions*, so unlike a blog, it can keep improving. Like any open source effort, we combine efforts but also review to ensure high quality.\n\nScope\n-----\n\n-\tCurrently, this guide covers selected “core” services, such as EC2, S3, Load Balancers, EBS, and IAM, and partial details and tips around other services. We expect it to expand.\n-\tIt is not a tutorial, but rather a collection of information you can read and return to. It is for both beginners and the experienced.\n-\tThe goal of this guide is to be:\n\t-\t**Brief:** Keep it dense and use links\n\t-\t**Practical:** Basic facts, concrete details, advice, gotchas, and other “folk knowledge”\n\t-\t**Current:** We can keep updating it, and anyone can contribute improvements\n\t-\t**Thoughtful:** The goal is to be helpful rather than present dry facts. Thoughtful opinion with rationale is welcome. Suggestions, notes, and opinions based on real experience can be extremely valuable. (We believe this is both possible with a guide of this format, unlike in some [other venues](http://meta.stackexchange.com/questions/201994/is-there-a-place-to-ask-opinion-based-questions).)\n-\tThis guide is not sponsored by AWS or AWS-affiliated vendors. It is written by and for engineers who use AWS.\n\nLegend\n------\n\n-\t📒 Marks standard/official AWS pages and docs\n-\t🔹 Important or often overlooked tip\n-\t❗ “Serious” gotcha (used where risks or time or resource costs are significant: critical security risks, mistakes with significant financial cost, or poor architectural choices that are fundamentally difficult to correct)\n-\t🔸 “Regular” gotcha, limitation, or quirk (used where consequences are things not working, breaking, or not scaling gracefully)\n-\t📜 Undocumented feature (folklore)\n-\t🐥 Relatively new (and perhaps immature) services or features\n-\t⏱ Performance discussions\n-\t⛓ Lock-in: Products or decisions that are likely to tie you to AWS in a new or significant way — that is, later moving to a non-AWS alternative would be costly in terms of engineering effort\n-\t🚪 Alternative non-AWS options\n-\t💸 Cost issues, discussion, and gotchas\n-\t🕍 A mild warning attached to “full solution” or opinionated frameworks that may take significant time to understand and/or might not fit your needs exactly; the opposite of a point solution (the cathedral is a nod to [Raymond’s metaphor](https://en.wikipedia.org/wiki/The_Cathedral_and_the_Bazaar)\\)\n-\t📗📘📙 Colors indicate basics, tips, and gotchas, respectively.\n-\t🚧 Areas where correction or improvement are needed (possibly with link to an issue — do help!)\n\nGeneral Information\n-------------------\n\n### When to Use AWS\n\n-\t[AWS](https://en.wikipedia.org/wiki/Amazon_Web_Services) is the dominant public cloud computing provider.\n\t-\tIn general, “[cloud computing](https://en.wikipedia.org/wiki/Cloud_computing)” can refer to one of three types of cloud: “public,” “private,” and “hybrid.” AWS is a public cloud provider, since anyone can use it. Private clouds are within a single (usually large) organization. Many companies use a hybrid of private and public clouds.\n\t-\tThe core features of AWS are [infrastructure-as-a-service](https://en.wikipedia.org/wiki/Cloud_computing#Infrastructure_as_a_service_.28IaaS.29) (IaaS) — that is, virtual machines and supporting infrastructure. Other cloud service models include [platform-as-a-service](https://en.wikipedia.org/wiki/Cloud_computing#Platform_as_a_service_.28PaaS.29) (PaaS), which typically are more fully managed services that deploy customers’ applications, or [software-as-a-service](https://en.wikipedia.org/wiki/Cloud_computing#Software_as_a_service_.28SaaS.29) (SaaS), which are cloud-based applications. AWS does offer a few products that fit into these other models, too.\n\t-\tIn business terms, with infrastructure-as-a-service you have a variable cost model — it is [OpEx, not CapEx](http://www.investopedia.com/ask/answers/020915/what-difference-between-capex-and-opex.asp) (though some [pre-purchased contracts](https://aws.amazon.com/ec2/purchasing-options/reserved-instances/) are still CapEx).\n  - AWS’s TTM revenue was [**$37.549 billion**](https://ir.aboutamazon.com/news-release/news-release-details/2020/Amazoncom-Announces-First-Quarter/default.aspx) as of Q1 2020 according to their earnings results (slide 14 in the linked deck), or roughly **14%** of Amazon.com’s total revenue (slide 11 in the same deck) for the same TTM period.\n-\t**Main reasons to use AWS:**\n\t-\tIf your company is building systems or products that may need to scale\n\t-\tand you have technical know-how\n\t-\tand you want the most flexible tools\n\t-\tand you’re not significantly tied into different infrastructure already\n\t-\tand you don’t have internal, regulatory, or compliance reasons you can’t use a public cloud-based solution\n\t-\tand you’re not on a Microsoft-first tech stack\n\t-\tand you don’t have a specific reason to use Google Cloud\n\t-\tand you can afford, manage, or negotiate its somewhat higher costs\n\t-\t... then AWS is likely a good option for your company.\n-\tEach of those reasons above might point to situations where other services are preferable. In practice, many, if not most, tech startups as well as a number of modern large companies can or already do benefit from using AWS. Many large enterprises are partly migrating internal infrastructure to Azure, Google Cloud, and AWS.\n-\t**Costs:** Billing and cost management are such big topics that we have [an entire section on this](#billing-and-cost-management).\n-\t🔹**EC2 vs. other services:** Most users of AWS are most familiar with [EC2](#ec2), AWS’ flagship virtual server product, and possibly a few others like S3 and CLBs. But AWS products now extend far beyond basic IaaS, and often companies do not properly understand or appreciate all the many AWS services and how they can be applied, due to the [sharply growing](#which-services-to-use) number of services, their novelty and complexity, branding confusion, and fear of ⛓lock-in to proprietary AWS technology. Although a bit daunting, it’s important for technical decision-makers in companies to understand the breadth of the AWS services and make informed decisions. (We hope this guide will help.)\n-\t🚪**AWS vs. other cloud providers:** While AWS is the dominant IaaS provider (31% market share in [this 2016 estimate](https://www.srgresearch.com/articles/aws-remains-dominant-despite-microsoft-and-google-growth-surges)), there is significant competition and alternatives that are better suited to some companies. [This Gartner report](https://www.gartner.com/doc/reprints?id=1-2G2O5FC&ct=150519&st=sb) has a good overview of the major cloud players :\n\t-\t[**Google Cloud Platform**](https://cloud.google.com/). GCP arrived later to market than AWS, but has vast resources and is now used widely by many companies, including a few large ones. It is gaining market share. Not all AWS services have similar or analogous services in GCP. And vice versa: In particular, GCP offers some more advanced machine learning-based services like the [Vision](https://cloud.google.com/vision/), [Speech](https://cloud.google.com/speech/), and [Natural Language](https://cloud.google.com/natural-language/) APIs. It’s not common to switch once you’re up and running, but it does happen: [Spotify migrated](http://www.wsj.com/articles/google-cloud-lures-amazon-web-services-customer-spotify-1456270951) from AWS to Google Cloud. There is more discussion [on Quora](https://www.quora.com/What-are-the-reasons-to-choose-AWS-over-Google-Cloud-or-vice-versa-for-a-high-traffic-web-application) about relative benefits. Of particular note is that VPCs in GCP are [global by default](https://cloud.google.com/vpc/) with subnetworks per region, while AWS’ VPCs have to live within a particular region. This gives GCP an edge if you’re designing applications with geo-replication from the beginning. It’s also possible to [share one GCP VPC](https://cloud.google.com/compute/docs/shared-vpc/) between multiple projects (roughly analogous to AWS accounts), while in AWS you’d have to peer them. It’s also possible to [peer GCP VPCs](https://cloud.google.com/compute/docs/vpc/vpc-peering) in a similar manner to how it’s done in AWS.\n\t-\t[**Microsoft Azure**](https://azure.microsoft.com/en) is the de facto choice for companies and teams that are focused on a Microsoft stack, and it has now placed significant emphasis on Linux as well\n\t-\tIn **China**, AWS’ footprint is relatively small. The market is dominated by Alibaba’s [Alibaba Cloud](https://www.alibabacloud.com/), formerly called [Aliyun](https://intl.aliyun.com/).\n\t-\tCompanies at (very) large scale may want to reduce costs by managing their own infrastructure. For example, [Dropbox migrated](https://news.ycombinator.com/item?id=11282948) to their own infrastructure.\n\t-\tOther cloud providers such as [Digital Ocean](https://www.digitalocean.com/) offer similar services, sometimes with greater ease of use, more personalized support, or lower cost. However, none of these match the breadth of products, mind-share, and market domination AWS now enjoys.\n\t-\tTraditional managed hosting providers such as [Rackspace](https://www.rackspace.com/) offer cloud solutions as well.\n-\t🚪**AWS vs. PaaS:** If your goal is just to put up a single service that does something relatively simple, and you’re trying to minimize time managing operations engineering, consider a [platform-as-a-service](https://en.wikipedia.org/wiki/Platform_as_a_service) such as [Heroku](https://www.heroku.com/). The AWS approach to PaaS, Elastic Beanstalk, is arguably more complex, especially for simple use cases.\n-\t🚪**AWS vs. web hosting:** If your main goal is to host a website or blog, and you don’t expect to be building an app or more complex service, you may wish consider one of the myriad [web hosting services](https://www.google.com/search?q=web+hosting).\n-\t🚪**AWS vs. managed hosting:** Traditionally, many companies pay [managed hosting](https://en.wikipedia.org/wiki/Dedicated_hosting_service) providers to maintain physical servers for them, then build and deploy their software on top of the rented hardware. This makes sense for businesses who want direct control over hardware, due to legacy, performance, or special compliance constraints, but is usually considered old fashioned or unnecessary by many developer-centric startups and younger tech companies.\n-\t**Complexity:** AWS will let you build and scale systems to the size of the largest companies, but the complexity of the services when used at scale requires significant depth of knowledge and experience. Even very simple use cases often require more knowledge to do “right” in AWS than in a simpler environment like Heroku or Digital Ocean. (This guide may help!)\n-\t**Geographic locations:** AWS has data centers in [over a dozen geographic locations](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions), known as **regions**, in Europe, East Asia, North and South America, and now Australia and India. It also has many more **edge locations** globally for reduced latency of services like CloudFront.\n\t-\tSee the [current list](https://aws.amazon.com/about-aws/global-infrastructure/) of regions and edge locations, including upcoming ones.\n\t-\tIf your infrastructure needs to be in close physical proximity to another service for latency or throughput reasons (for example, latency to an ad exchange), viability of AWS may depend on the location.\n-\t⛓**Lock-in:** As you use AWS, it’s important to be aware when you are depending on AWS services that do not have equivalents elsewhere.\n\t-\tLock-in may be completely fine for your company, or a significant risk. It’s important from a business perspective to make this choice explicitly, and consider the cost, operational, business continuity, and competitive risks of being tied to AWS. AWS is such a dominant and reliable vendor, many companies are comfortable with using AWS to its full extent. Others can tell stories about the [dangers of “cloud jail” when costs spiral](http://firstround.com/review/the-three-infrastructure-mistakes-your-company-must-not-make/).\n\t-\tGenerally, the more AWS services you use, the more lock-in you have to AWS — that is, the more engineering resources (time and money) it will take to change to other providers in the future.\n\t-\tBasic services like virtual servers and standard databases are usually easy to migrate to other providers or on premises. Others like load balancers and IAM are specific to AWS but have close equivalents from other providers. The key thing to consider is whether engineers are architecting systems around specific AWS services that are not open source or relatively interchangeable. For example, Lambda, API Gateway, Kinesis, Redshift, and DynamoDB do not have substantially equivalent open source or commercial service equivalents, while EC2, RDS (MySQL or Postgres), EMR, and ElastiCache more or less do. (See more [below](#which-services-to-use), where these are noted with ⛓.)\n-\t**Combining AWS and other cloud providers:** Many customers combine AWS with other non-AWS services. For example, legacy systems or secure data might be in a managed hosting provider, while other systems are AWS. Or a company might only use S3 with another provider doing everything else. However small startups or projects starting fresh will typically stick to AWS or Google Cloud only.\n-\t**Hybrid cloud:** In larger enterprises, it is common to have [hybrid deployments](https://aws.amazon.com/enterprise/hybrid/) encompassing private cloud or on-premises servers and AWS — or other enterprise cloud providers like [IBM](https://www.ibm.com/it-infrastructure/solutions/hybrid-cloud)/[Bluemix](http://www.ibm.com/cloud-computing/bluemix/hybrid/), [Microsoft](https://www.microsoft.com/en-us/cloud-platform/hybrid-cloud)/[Azure](https://azure.microsoft.com/en-us/overview/azure-stack/), [NetApp](http://www.netapp.com/us/solutions/cloud/hybrid-cloud/), or [EMC](http://www.emc.com/en-us/cloud/hybrid-cloud-computing/index.htm).\n-\t**Major customers:** Who uses AWS and Google Cloud?\n\t-\tAWS’s [list of customers](https://aws.amazon.com/solutions/case-studies/) includes large numbers of mainstream online properties and major brands, such as Netflix, Pinterest, Spotify (moving to Google Cloud), Airbnb, Expedia, Yelp, Zynga, Comcast, Nokia, and Bristol-Myers Squibb.\n\t-\tAzure’s [list of customers](https://azure.microsoft.com/en-us/case-studies/) includes companies such as NBC Universal, 3M and Honeywell Inc.\n\t-\tGoogle Cloud’s [list of customers](https://cloud.google.com/customers/) is large as well, and includes a few mainstream sites, such as [Snapchat](http://www.businessinsider.com/snapchat-is-built-on-googles-cloud-2014-1), Best Buy, Domino’s, and Sony Music.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Which Services to Use\n\n-\tAWS offers a *lot* of different services — [about a hundred](https://aws.amazon.com/products/) at last count.\n-\tMost customers use a few services heavily, a few services lightly, and the rest not at all. What services you’ll use depends on your use cases. Choices differ substantially from company to company.\n-\t**Immature and unpopular services:** Just because AWS has a service that sounds promising, it doesn’t mean you should use it. Some services are very narrow in use case, not mature, are overly opinionated, or have limitations, so building your own solution may be better. We try to give a sense for this by breaking products into categories.\n-\t**Must-know infrastructure:** Most typical small to medium-size users will focus on the following services first. If you manage use of AWS systems, you likely need to know at least a little about all of these. (Even if you don’t use them, you should learn enough to make that choice intelligently.)\n\t-\t[IAM](#security-and-iam): User accounts and identities (you need to think about accounts early on!)\n\t-\t[EC2](#ec2): Virtual servers and associated components, including:\n\t\t-\t[AMIs](#amis): Machine Images\n\t\t-\t[Load Balancers](#load-balancers): CLBs and ALBs\n\t\t-\t[Autoscaling](#auto-scaling): Capacity scaling (adding and removing servers based on load)\n\t\t-\t[EBS](#ebs): Network-attached disks\n\t\t-\t[Elastic IPs](#elastic-ips): Assigned IP addresses\n\t-\t[S3](#s3): Storage of files\n\t-\t[Route 53](#route-53): DNS and domain registration\n\t-\t[VPC](#vpcs-network-security-and-security-groups): Virtual networking, network security, and co-location; you automatically use\n\t-\t[CloudFront](#cloudfront): CDN for hosting content\n\t-\t[CloudWatch](#cloudwatch): Alerts, paging, monitoring\n-\t**Managed services:** Existing software solutions you could run on your own, but with managed deployment:\n\t-\t[RDS](#rds): Managed relational databases (managed MySQL, Postgres, and Amazon’s own Aurora database)\n\t-\t[EMR](#emr): Managed Hadoop\n\t-\t[Elasticsearch](https://aws.amazon.com/elasticsearch-service/): Managed Elasticsearch\n\t-\t[ElastiCache](https://aws.amazon.com/elasticache/): Managed Redis and Memcached\n-\t**Optional but important infrastructure:** These are key and useful infrastructure components that are less widely known and used. You may have legitimate reasons to prefer alternatives, so evaluate with care to be sure they fit your needs:\n\t-\t⛓[Lambda](#lambda): Running small, fully managed tasks “serverless”\n\t-\t[CloudTrail](https://aws.amazon.com/cloudtrail/): AWS API logging and audit (often neglected but important)\n\t-\t⛓🕍[CloudFormation](#cloudformation): Templatized configuration of collections of AWS resources\n\t-\t🕍[Elastic Beanstalk](https://aws.amazon.com/elasticbeanstalk/): Fully managed (PaaS) deployment of packaged Java, .NET, PHP, Node.js, Python, Ruby, Go, and Docker applications\n\t-\t🐥[EFS](#efs): Network filesystem compatible with NFSv4.1\n\t-\t⛓🕍[ECS](#ecs): Docker container/cluster management (note Docker can also be used directly, without ECS)\n\t-   🕍 [EKS](#eks): Kubernetes (K8) Docker Container/Cluster management\n\t-\t⛓[ECR](https://aws.amazon.com/ecr/): Hosted private Docker registry\n\t-\t🐥[Config](https://aws.amazon.com/config/): AWS configuration inventory, history, change notifications\n\t-\t🐥[X-Ray](https://aws.amazon.com/xray/): Trace analysis and debugging for distributed applications such as microservices.\n-\t**Special-purpose infrastructure:** These services are focused on specific use cases and should be evaluated if they apply to your situation. Many also are proprietary architectures, so tend to tie you to AWS.\n\t-\t⛓[DynamoDB](#dynamodb): Low-latency NoSQL key-value store\n\t-\t⛓[Glacier](#glacier): Slow and cheap alternative to S3\n\t-\t⛓[Kinesis](https://aws.amazon.com/kinesis/): Streaming (distributed log) service\n\t-\t⛓[SQS](https://aws.amazon.com/sqs/): Message queueing service\n\t-\t⛓[Redshift](#redshift): Data warehouse\n\t-\t🐥[QuickSight](https://aws.amazon.com/quicksight/): Business intelligence service\n\t-\t[SES](https://aws.amazon.com/ses/): Send and receive e-mail for marketing or transactions\n\t-\t⛓[API Gateway](https://aws.amazon.com/api-gateway/): Proxy, manage, and secure API calls\n\t-\t⛓[IoT](#iot): Manage bidirectional communication over HTTP, WebSockets, and MQTT between AWS and clients (often but not necessarily “things” like appliances or sensors)\n\t-\t⛓[WAF](https://aws.amazon.com/waf/): Web firewall for CloudFront to deflect attacks\n\t-\t⛓[KMS](#kms): Store and manage encryption keys securely\n\t-\t[Inspector](https://aws.amazon.com/inspector/): Security audit\n\t-\t[Trusted Advisor](https://aws.amazon.com/premiumsupport/trustedadvisor/): Automated tips on reducing cost or making improvements\n\t-\t🐥[Certificate Manager](https://aws.amazon.com/certificate-manager/): Manage SSL/TLS certificates for AWS services\n\t-\t🐥⛓[Fargate](https://aws.amazon.com/fargate/): Docker containers management, backend for ECS and EKS\n-\t**Compound services:** These are similarly specific, but are full-blown services that tackle complex problems and may tie you in. Usefulness depends on your requirements. If you have large or significant need, you may have these already managed by in-house systems and engineering teams.\n\t-\t[Machine Learning](https://aws.amazon.com/machine-learning/): Machine learning model training and classification\n\t-\t[Lex](https://aws.amazon.com/lex/): Automatic speech recognition (ASR) and natural language understanding (NLU)\n\t-\t[Polly](https://aws.amazon.com/polly/): Text-to-speech engine in the cloud\n\t-\t[Rekognition](https://aws.amazon.com/rekognition/): Service for image recognition\n\t-\t⛓🕍[Data Pipeline](https://aws.amazon.com/datapipeline/): Managed ETL service\n\t-\t⛓🕍[SWF](https://aws.amazon.com/swf/): Managed state tracker for distributed polyglot job workflow\n\t-\t⛓🕍[Lumberyard](https://aws.amazon.com/lumberyard/): 3D game engine\n-\t**Mobile/app development:**\n\t-\t[SNS](https://aws.amazon.com/sns/): Manage app push notifications and other end-user notifications\n\t-\t⛓🕍[Cognito](https://aws.amazon.com/cognito/): User authentication via Facebook, Twitter, etc.\n\t-\t[Device Farm](https://aws.amazon.com/device-farm/): Cloud-based device testing\n\t-\t[Mobile Analytics](https://aws.amazon.com/mobileanalytics/): Analytics solution for app usage\n\t-\t🕍[Mobile Hub](https://aws.amazon.com/mobile/): Comprehensive, managed mobile app framework\n-\t**Enterprise services:** These are relevant if you have significant corporate cloud-based or hybrid needs. Many smaller companies and startups use other solutions, like Google Apps or Box. Larger companies may also have their own non-AWS IT solutions.\n\t-\t[AppStream](https://aws.amazon.com/appstream/): Windows apps in the cloud, with access from many devices\n\t-\t[Workspaces](https://aws.amazon.com/workspaces/): Windows desktop in the cloud, with access from many devices\n\t-\t[WorkDocs](https://aws.amazon.com/workdocs/) (formerly Zocalo): Enterprise document sharing\n\t-\t[WorkMail](https://aws.amazon.com/workmail/): Enterprise managed e-mail and calendaring service\n\t-\t[Directory Service](https://aws.amazon.com/directoryservice/): Microsoft Active Directory in the cloud\n\t-\t[Direct Connect](https://aws.amazon.com/directconnect/): Dedicated network connection between office or data center and AWS\n\t-\t[Storage Gateway](https://aws.amazon.com/storagegateway/): Bridge between on-premises IT and cloud storage\n\t-\t[Service Catalog](https://aws.amazon.com/servicecatalog/): IT service approval and compliance\n-\t**Probably-don't-need-to-know services:** Bottom line, our informal polling indicates these services are just not broadly used — and often for good reasons:\n\t-\t[Snowball](https://aws.amazon.com/importexport/): If you want to ship petabytes of data into or out of Amazon using a physical appliance, read on.\n\t-\t[Snowmobile](https://aws.amazon.com/snowmobile/): Appliances are great, but if you've got exabyte scale data to get into Amazon, nothing beats a tractor trailer full of drives.\n\t-\t[CodeCommit](https://aws.amazon.com/codecommit/): Git service. You’re probably already using GitHub or your own solution ([Stackshare](http://stackshare.io/stackups/github-vs-bitbucket-vs-aws-codecommit) has informal stats).\n\t-\t🕍[CodePipeline](https://aws.amazon.com/codepipeline/): Continuous integration. You likely have another solution already.\n\t-\t🕍[CodeDeploy](https://aws.amazon.com/codedeploy/): Deployment of code to EC2 servers. Again, you likely have another solution.\n\t-\t🕍[OpsWorks](https://aws.amazon.com/opsworks/): Management of your deployments using Chef or (as of November 2017) Puppet Enterprise.\n-\t[AWS in Plain English](https://www.expeditedssl.com/aws-in-plain-english) offers more friendly explanation of what all the other different services are.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Tools and Services Market Landscape\n\nThere are now enough cloud and “big data” enterprise companies and products that few can keep up with the market landscape.\n\nWe’ve assembled a landscape of a few of the services. This is far from complete, but tries to emphasize services that are popular with AWS practitioners — services that specifically help with AWS, or a complementary, or tools almost anyone using AWS must learn.\n\n![Popular Tools and Services for AWS Practitioners](figures/aws-market-landscape.png)\n\n🚧 *Suggestions to improve this figure? Please [file an issue](CONTRIBUTING.md).*\n\n\n[Back to top :arrow_up:](#table-of-contents)\n### Common Concepts\n\n-\t📒 The AWS [**General Reference**](https://docs.aws.amazon.com/general/latest/gr/Welcome.html) covers a bunch of common concepts that are relevant for multiple services.\n-\tAWS allows deployments in [**regions**](https://docs.aws.amazon.com/general/latest/gr/rande.html), which are isolated geographic locations that help you reduce latency or offer additional redundancy. Regions contain availability zones(AZs), which are typically the first tool of choice for [high availability](#high-availability)). AZs are [physically separate from one another](https://www.youtube.com/watch?v=JIQETrFC_SQ&feature=youtu.be&t=1428) even within the same region, and [may span multiple physical data centers](https://blog.rackspace.com/aws-101-regions-availability-zones). While they are connected via low latency links, natural disasters afflicting one should not affect others.\n-\tEach service has API **endpoints** for each region. Endpoints differ from service to service and not all services are available in each region, as listed in [these tables](https://docs.aws.amazon.com/general/latest/gr/rande.html).\n-\t[**Amazon Resource Names (ARNs)**](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) are specially formatted identifiers for identifying resources. They start with 'arn:' and are used in many services, and in particular for IAM policies.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Service Matrix\n\nMany services within AWS can at least be compared with Google Cloud offerings or with internal Google services. And often times you could assemble the same thing yourself with open source software. This table is an effort at listing these rough correspondences. (Remember that this table is imperfect as in almost every case there are subtle differences of features!)\n\n| Service                       | AWS                                                                          | Google Cloud                 | Google Internal | Microsoft Azure                    | Other providers                   | Open source “build your own”                               | Openstack     |\n|-------------------------------|------------------------------------------------------------------------------|------------------------------|-----------------|------------------------------------|-----------------------------------|------------------------------------------------------------|------------------------------------------------------------|\n| Virtual server                | EC2                                                                          | Compute Engine (GCE)         |                 | Virtual Machine                    | DigitalOcean                      | OpenStack                                                  | Nova |\n| PaaS                          | Elastic Beanstalk                                                            | App Engine                   | App Engine      | Web Apps                           | Heroku, AppFog, OpenShift | Meteor, AppScale, Cloud Foundry, Convox                    |\n| Serverless, microservices     | Lambda, API Gateway                                                          | Functions                    |                 | Function Apps                      | PubNub Blocks, Auth0 Webtask      | Kong, Tyk                                                  | Qinling |\n| Container, cluster manager    | ECS, EKS, Fargate                                                                 | Container Engine, Kubernetes | Borg or Omega   | Container Service                  |                                   | Kubernetes, Mesos, Aurora                                  |  Zun |\n| Object storage                  | S3                                                                           | Cloud Storage                | GFS             | Storage Account                    | DigitalOcean Spaces               | Swift, HDFS, Minio                                         | Swift |\n| Block storage                 | EBS                                                                          | Persistent Disk              |                 | Storage Account                    | DigitalOcean Volumes              | NFS                                                        | Cinder |\n| SQL datastore                 | RDS                                                                          | Cloud SQL                    |                 | SQL Database                       |                                   | MySQL, PostgreSQL                                          | Trove (stores NoSQL as well) |\n| Sharded RDBMS                 |                                                                              | Cloud Spanner                | F1, Spanner     | Azure Database for PostgreSQL - Hyperscale (Citus) |                                   | Crate.io, CockroachDB                                      |\n| Bigtable                      |                                                                              | Cloud Bigtable               | Bigtable        |                                    |                                   | HBase                                                      |\n| Key-value store, column store | DynamoDB                                                                     | Cloud Datastore              | Megastore       | Tables, DocumentDB                 |                                   | Cassandra, CouchDB, RethinkDB, Redis                       |\n| Memory cache                  | ElastiCache                                                                  | App Engine Memcache          |                 | Redis Cache                        |                                   | Memcached, Redis                                           |\n| Search                        | CloudSearch, Elasticsearch (managed)                                         |                              |                 | Search                             | Algolia, QBox, Elastic Cloud                     | Elasticsearch, Solr                                        |\n| Data warehouse                | Redshift                                                                     | BigQuery                     | Dremel          | SQL Data Warehouse                 | Oracle, IBM, SAP, HP, many others | Greenplum                                                  |\n| Business intelligence         | QuickSight                                                                   | Data Studio 360               |                 | Power BI                           | Tableau                           |                                                            |\n| Lock manager                  | [DynamoDB (weak)](https://gist.github.com/ryandotsmith/c95fd21fab91b0823328) |                              | Chubby          | Lease blobs in Storage Account     |                                   | ZooKeeper, Etcd, Consul                                    |\n| Message broker                | SQS, SNS, IoT                                                                | Pub/Sub                      | PubSub2         | Service Bus                        |                                   | RabbitMQ, Kafka, 0MQ                                       |\n| Streaming, distributed log    | Kinesis                                                                      | Dataflow                     | PubSub2         | Event Hubs                         |                                   | Kafka Streams, Apex, Flink, Spark Streaming, Storm         |\n| MapReduce                     | EMR                                                                          | Dataproc                     | MapReduce       | HDInsight, DataLake Analytics      | Qubole                            | Hadoop                                                     |\n| Monitoring                    | CloudWatch                                                                   | Stackdriver Monitoring       | Borgmon         | Monitor                            |                                   | Prometheus(?)                                              |\n| Tracing                       | X-Ray                                                                        | Stackdriver Trace            |                 | Monitor (Application Insights)     |  DataDog, New Relic, Epsagon      | Zipkin, Jaeger, Appdash\n| Metric management             |                                                                              |                              | Borgmon, TSDB   | Application Insights               |                                   | Graphite, InfluxDB, OpenTSDB, Grafana, Riemann, Prometheus |\n| CDN                           | CloudFront                                                                   | Cloud CDN                    |                 | CDN                                |  Akamai, Fastly, Cloudflare, Limelight Networks                                 | Apache Traffic Server                                      |\n| Load balancer                 | CLB/ALB                                                                      | Load Balancing               | GFE             | Load Balancer, Application Gateway |                                   | nginx, HAProxy, Apache Traffic Server                      |\n| DNS                           | Route53                                                                      | DNS                          |                 | DNS                                |                                   | bind                                                       |\n| Email                         | SES                                                                          |                              |                 |                                    | Sendgrid, Mandrill, Postmark      |                                                            |\n| Git hosting                   | CodeCommit                                                                   | Cloud Source Repositories    |                 | Visual Studio Team Services        | GitHub, BitBucket                 | GitLab                                                     |\n| User authentication           | Cognito                                                                      |    Firebase Authentication                          |                 | Azure Active Directory             |                                   | oauth.io                                                   |\n| Mobile app analytics          | Mobile Analytics                                                             | Firebase Analytics           |                 | HockeyApp                          | Mixpanel                          |                                                            |\n| Mobile app testing            | Device Farm                                                                  | Firebase Test Lab            |                 | Xamarin Test Cloud                 | BrowserStack, Sauce Labs, Testdroid                                                            |\n| Managing SSL/TLS certificates            | Certificate Manager                                                                  |                |                 |                 | Let's Encrypt, Comodo, Symantec, GlobalSign |\n| Automatic speech recognition and natural language understanding            | Transcribe (ASR), Lex (NLU)     | Cloud Speech API, Natural Language API             |                 | Cognitive services                | AYLIEN Text Analysis API, Ambiverse Natural Language Understanding API  |Stanford's Core NLP Suite, Apache OpenNLP, Apache UIMA, spaCy |\n| Text-to-speech engine in the cloud            | Polly                                                                  |                |                 |                 |Nuance, Vocalware, IBM | Mimic, eSpeak, MaryTTS |\n| Image recognition            | Rekognition                                                            |   Vision API              |                |Cognitive services                 | IBM Watson, Clarifai |TensorFlow, OpenCV |\n| OCR (Text recognition)       | Textract (documents), Rekognition (photographs)                               | Cloud Vision API             |                 | Computer Vision API                |                                   | Tesseract                                                  |\n| Language Translation          | Translate                                                                    | Translate                    |                 | Translator Text API                |                                   | Apertium                                                   |\n| File Share and Sync          | WorkDocs                                                                   |   Google Docs                 |                 |OneDrive                  |       Dropbox, Box, Citrix File Share                  |ownCloud |\n| Machine Learning          | SageMaker, DeepLens, ML                                                                   |   ML Engine, Auto ML                 |                 |ML Studio                  |       Watson ML                  |  |\n| Data Loss Prevention         | Macie                                                                         | Cloud Data Loss Prevention   |                | Azure Information Protection        |                                   |                                                            |\n\n🚧 [*Please help fill this table in.*](CONTRIBUTING.md)\n\nSelected resources with more detail on this chart:\n\n-\tGoogle internal: [MapReduce](http://research.google.com/archive/mapreduce.html), [Bigtable](http://research.google.com/archive/bigtable.html), [Spanner](http://research.google.com/archive/spanner.html), [F1 vs Spanner](http://highscalability.com/blog/2013/10/8/f1-and-spanner-holistically-compared.html), [Bigtable vs Megastore](http://perspectives.mvdirona.com/2008/07/google-megastore/)\n\n[Back to top :arrow_up:](#table-of-contents)\n### AWS Product Maturity and Releases\n\nIt’s important to know the maturity of each AWS product. Here is a mostly complete list of first release date, with links to the [release notes](https://aws.amazon.com/releasenotes/). Most recently released services are first. Not all services are available in all regions; see [this table](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/).\n\n| Service                                                                                                    | Original release | Availability                                                                  | CLI Support | HIPAA Compliant | PCI-DSS Compliant |\n|------------------------------------------------------------------------------------------------------------|------------------|-------------------------------------------------------------------------------|:-----------:|:---------------:|:-----------------:|\n| 🐥[X-Ray](https://aws.amazon.com/releasenotes/AWS-X-Ray?browse=1)\t\t\t\t\t\t\t\t\t\t  | 2016-12          | General\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  |✓            |✓                |✓                   |\n| 🐥[Lex](https://aws.amazon.com/releasenotes/Amazon-Lex?browse=1)                                           | 2016-11          | Preview                                                                       |             |                 |                   |\n| 🐥[Polly](https://aws.amazon.com/releasenotes/Amazon-Polly?browse=1)                                       | 2016-11          | General                                                                       |✓            |✓                |✓                   |\n| 🐥[Rekognition](https://aws.amazon.com/releasenotes/Amazon-Rekognition?browse=1) \t\t\t\t\t\t\t | 2016-11          | General                                                                       |✓            |✓\t\t\t\t |✓  \t\t\t\t|\n| 🐥[Athena](http://docs.aws.amazon.com/athena/latest/ug/what-is.html) \t\t\t\t\t\t\t\t\t\t | 2016-11          | General                                                                       |✓             |✓               |✓\t\t\t\t\t|\n| 🐥[Batch](http://docs.aws.amazon.com/batch/latest/userguide/what-is-batch.html) \t\t\t\t\t\t\t | 2016-11          | General                                                                       |✓             |✓\t\t\t|✓\t\t\t\t\t|\n| 🐥[Database Migration Service](https://aws.amazon.com/releasenotes/AWS-Database-Migration-Service?browse=1) | 2016-03          | General                                                                      |              | ✓         \t\t|\t✓    \t\t\t|\n| 🐥[Certificate Manager](https://aws.amazon.com/blogs/aws/new-aws-certificate-manager-deploy-ssltls-based-apps-on-aws/) | 2016-01          | General                                                            | ✓\t\t   |✓\t\t\t|✓\t\t\t\t\t|\n| 🐥[IoT](https://aws.amazon.com/blogs/aws/aws-iot-now-generally-available/)                                  | 2015-08          | General                                                                       | ✓           |✓\t\t\t|✓<sup>[13](#user-content-pci-iot)</sup>\t\t\t\t\t|\n| 🐥[WAF](https://aws.amazon.com/releasenotes/AWS-WAF?browse=1)                                               | 2015-10          | General                                                                       | ✓           | ✓         \t\t|\t✓    \t\t\t|\n| 🐥[Data Pipeline](https://aws.amazon.com/releasenotes/AWS-Data-Pipeline?browse=1)                           | 2015-10          | General                                                                       | ✓           |\t\t\t\t|\t\t\t\t\t|\n| 🐥[Elasticsearch](https://aws.amazon.com/releasenotes/Amazon-Elasticsearch-Service?browse=1)                | 2015-10          | General                                                                       | ✓           |✓\t\t\t|✓\t\t\t\t\t|\n| 🐥[Aurora](https://aws.amazon.com/releasenotes/2775579329314699)                                            | 2015-07          | General                                                                       | ✓           | ✓<sup>[3](#user-content-hipaa-aurora)</sup> |\t✓<sup>[3](#user-content-hipaa-aurora)</sup>\t\t\t|\n| 🐥[Service Catalog](https://aws.amazon.com/releasenotes/AWS-Service-Catalog?browse=1)                       | 2015-07          | General                                                                       | ✓           |✓\t\t\t|✓\t\t\t\t\t|\n| 🐥[Device Farm](https://aws.amazon.com/releasenotes/AWS-Device-Farm?browse=1)                         \t  | 2015-07          | General                                                                       | ✓           |\t\t\t\t|\t\t\t\t\t|\n| 🐥[CodePipeline](https://aws.amazon.com/releasenotes/AWS-CodePipeline?browse=1)                             | 2015-07          | General                                                                       | ✓           |✓\t\t\t|\t\t\t\t\t|\n| 🐥[CodeCommit](https://aws.amazon.com/releasenotes/AWS-CodeCommit?browse=1)                                 | 2015-07          | General                                                                       | ✓           |✓\t\t\t|✓\t\t\t\t\t|\n| 🐥[API Gateway](https://aws.amazon.com/releasenotes/Amazon-API-Gateway?browse=1)                            | 2015-07          | General                                                                       | ✓           | ✓<sup>[1](#user-content-hipaa-apigateway)</sup>  |\t ✓ \t\t\t|\n| 🐥[Config](https://aws.amazon.com/releasenotes/AWS-Config?browse=1)                                         | 2015-06          | General                                                                       | ✓           |✓                |  ✓              |\n| 🐥[EFS](https://aws.amazon.com/releasenotes/Amazon-EFS?browse=1)                                            | 2015-05          | General                                                                       | ✓           |✓                |✓                  |\n| 🐥[Machine Learning](https://aws.amazon.com/releasenotes/AmazonML?browse=1)                                 | 2015-04          | General                                                                       | ✓           |                 |                  |\n| [Lambda](https://aws.amazon.com/releasenotes/AWS-Lambda?browse=1)                                          | 2014-11          | General                                                                       | ✓           |✓                |   ✓             |\n| [ECS](https://aws.amazon.com/ecs/release-notes/)                                                           | 2014-11          | General                                                                       | ✓           | ✓         \t\t|\t✓   \t\t\t|\n| [EKS](https://docs.aws.amazon.com/eks/latest/userguide/platform-versions.html)                                                           | 2018-06          | General                                                                       | ✓<sup>[12](#user-content-eks-cli)</sup>           |✓         \t\t|✓\t  \t\t\t|\n| [KMS](https://aws.amazon.com/releasenotes/AWS-KMS?browse=1)                                                | 2014-11          | General                                                                       | ✓           |✓                |   ✓             |\n| [CodeDeploy](https://aws.amazon.com/releasenotes/AWS-CodeDeploy?browse=1)                                  | 2014-11          | General                                                                       | ✓           |✓                |                  |\n| [Kinesis](https://aws.amazon.com/releasenotes/Amazon-Kinesis?browse=1)                                     | 2013-12          | General                                                                       | ✓           |✓                |   ✓<sup>[11](#user-content-pci-kinesis)</sup>    |\n| [CloudTrail](https://aws.amazon.com/releasenotes/AWS-CloudTrail?browse=1)                                  | 2013-11          | General                                                                       | ✓           |✓                |   ✓             |\n| [AppStream](https://aws.amazon.com/releasenotes/Amazon-AppStream?browse=1)                                 | 2013-11          | Preview                                                                       |             |✓                |                  |\n| [CloudHSM](https://aws.amazon.com/releasenotes/AWS-CloudHSM?browse=1)                                      | 2013-03          | General                                                                       | ✓           |✓                |   ✓            |\n| [Silk](https://aws.amazon.com/releasenotes/Amazon-Silk?browse=1)                                           | 2013-03          | Obsolete?                                                                     |             |                 |                  |\n| [OpsWorks](https://aws.amazon.com/releasenotes/AWS-OpsWorks?browse=1)                                      | 2013-02          | General                                                                       | ✓           |✓                |   ✓             |\n| [Redshift](https://aws.amazon.com/releasenotes/Amazon-Redshift?browse=1)                                   | 2013-02          | General                                                                       | ✓           | ✓         \t\t|\t✓   \t\t\t|\n| [Elastic Transcoder](https://aws.amazon.com/releasenotes/Amazon-Elastic-Transcoder?browse=1)               | 2013-01          | General                                                                       | ✓           |                 |                  |\n| [Glacier](https://aws.amazon.com/releasenotes/Amazon-Glacier?browse=1)                                     | 2012-08          | General                                                                       | ✓           | ✓         \t\t|\t✓\t    \t\t|\n| [CloudSearch](https://aws.amazon.com/releasenotes/Amazon-CloudSearch?browse=1)                             | 2012-04          | General                                                                       | ✓           |                 |                  |\n| [SWF](https://aws.amazon.com/releasenotes/Amazon-SWF?browse=1)                                             | 2012-02          | General                                                                       | ✓           |✓                | ✓                |\n| [Storage Gateway](https://aws.amazon.com/releasenotes/AWS-Storage-Gateway?browse=1)                        | 2012-01          | General                                                                       | ✓           |✓                |✓                  |\n| [DynamoDB](https://aws.amazon.com/releasenotes/Amazon-DynamoDB?browse=1)                                   | 2012-01          | General                                                                       | ✓           | ✓         \t\t|\t  ✓  \t\t\t|\n| [DirectConnect](https://aws.amazon.com/releasenotes/AWS-Direct-Connect?browse=1)                           | 2011-08          | General                                                                       | ✓           | ✓         \t\t|\t✓   \t\t\t|\n| [ElastiCache](https://aws.amazon.com/releasenotes/Amazon-ElastiCache?browse=1)                             | 2011-08          | General                                                                       | ✓           |✓<sup>[14](#user-content-pci-elasticache)</sup> |✓<sup>[14](#user-content-pci-elasticache)</sup>                  |\n| [CloudFormation](https://aws.amazon.com/releasenotes/AWS-CloudFormation?browse=1)                          | 2011-04          | General                                                                       | ✓           |✓                |  ✓              |\n| [SES](https://aws.amazon.com/releasenotes/Amazon-SES?browse=1)                                             | 2011-01          | General                                                                       | ✓           |✓                |                  |\n| [Elastic Beanstalk](https://aws.amazon.com/releasenotes/AWS-Elastic-Beanstalk?browse=1)                    | 2010-12          | General                                                                       | ✓           |✓                |  ✓              |\n| [Route 53](https://aws.amazon.com/releasenotes/Amazon-Route-53?browse=1)                                   | 2010-10          | General                                                                       | ✓           |✓                | ✓               |\n| [IAM](https://aws.amazon.com/releasenotes/AWS-Identity-and-Access-Management?browse=1)                     | 2010-09          | General                                                                       | ✓           |                 |  ✓              |\n| [SNS](https://aws.amazon.com/releasenotes/Amazon-SNS?browse=1)                                             | 2010-04          | General                                                                       | ✓           | ✓         \t\t| ✓\t\t\t\t\t|\n| [EMR](https://aws.amazon.com/releasenotes/Elastic-MapReduce?browse=1)                                      | 2010-04          | General                                                                       | ✓           | ✓         \t\t|\t✓   \t\t\t|\n| [RDS](https://aws.amazon.com/releasenotes/Amazon-RDS?browse=1)                                             | 2009-12          | General                                                                       | ✓           |✓<sup>[2](#user-content-hipaa-rds)</sup>        |✓<sup>[9](#user-content-pci-rds)</sup>\t\t\t\t|\n| [VPC](https://aws.amazon.com/releasenotes/Amazon-VPC?browse=1)                                             | 2009-08          | General                                                                       | ✓           | ✓         \t\t|\t✓   \t\t\t|\n| [Snowball](https://aws.amazon.com/releasenotes/AWS-ImportExport?browse=1)                                  | 2015-10          | General                                                                       | ✓           | ✓         \t\t|✓<sup>[15](#user-content-pci-snowball)</sup>\t\t\t\t\t|\n| [Snowmobile](https://aws.amazon.com/snowmobile/)                                                           | 2016-11          | General                                                                       |            |✓                |✓                  |\n| [CloudWatch](https://aws.amazon.com/releasenotes/CloudWatch?browse=1)                                      | 2009-05          | General                                                                       | ✓           |✓                |  ✓               |\n| [CloudFront](https://aws.amazon.com/releasenotes/CloudFront?browse=1)                                      | 2008-11          | General                                                                       | ✓           | ✓<sup>[4](#user-content-hipaa-cloudfront)</sup>        |  ✓\t\t\t\t|\n| [Fulfillment Web Service](https://aws.amazon.com/releasenotes/Amazon-FWS?browse=1)                         | 2008-03          | Obsolete?                                                                     |             |                 |                  |\n| [SimpleDB](https://aws.amazon.com/releasenotes/Amazon-SimpleDB?browse=1)                                   | 2007-12          | ❗[Nearly obsolete](https://forums.aws.amazon.com/thread.jspa?threadID=121711) | ✓           |                 |  ✓              |\n| [DevPay](https://aws.amazon.com/releasenotes/DevPay?browse=1)                                              | 2007-12          | General                                                                       |             |                 |                  |\n| [Flexible Payments Service](https://aws.amazon.com/releasenotes/Amazon-FPS?browse=1)                       | 2007-08          | Retired                                                                       |             |                 |                  |\n| [EC2](https://aws.amazon.com/releasenotes/Amazon-EC2?browse=1)                                             | 2006-08          | General                                                                       | ✓           | ✓<sup>[5](#user-content-hipaa-ec2sysmgr),[6](#user-content-hipaa-ec2ebs),[7](#user-content-hipaa-ec2elb)</sup>          |\t✓<sup>[6](#user-content-hipaa-ec2ebs),[7](#user-content-hipaa-ec2elb),[10](#user-content-pci-asg)</sup>\t\t\t|\n| [SQS](https://aws.amazon.com/releasenotes/Amazon-SQS?browse=1)                                             | 2006-07          | General                                                                       | ✓           | ✓         \t\t| ✓               |\n| [S3](https://aws.amazon.com/releasenotes/Amazon-S3?browse=1)                                               | 2006-03          | General                                                                       | ✓           | ✓<sup>[8](#user-content-hipaa-s3)</sup>   |\t✓   \t\t\t|\n| [Alexa Top Sites](https://aws.amazon.com/alexa-top-sites/)                                                 | 2006-01          | General ❗HTTP-only                                                            |             |                 |                  |\n| [Alexa Web Information Service](https://aws.amazon.com/awis/)                                              | 2005-10          | General ❗HTTP-only                                                            |             |                 |                  |\n\n[Back to top :arrow_up:](#table-of-contents)\n##### Footnotes\n<a name=\"user-content-hipaa-apigateway\">**1**</a>: Excludes use of Amazon API Gateway caching<br />\n<a name=\"user-content-hipaa-rds\">**2**</a>: RDS MySQL, Oracle, and PostgreSQL engines only<br />\n<a name=\"user-content-hipaa-aurora\">**3**</a>: MySQL-compatible Aurora edition only<br />\n<a name=\"user-content-hipaa-cloudfront\">**4**</a>: Excludes Lambda@Edge<br />\n<a name=\"user-content-hipaa-ec2sysmgr\">**5**</a>: Includes EC2 Systems Manager<br />\n<a name=\"user-content-hipaa-ec2ebs\">**6**</a>: Includes Elastic Block Storage (EBS)<br />\n<a name=\"user-content-hipaa-ec2elb\">**7**</a>: Includes Elastic Load Balancing<br />\n<a name=\"user-content-hipaa-s3\">**8**</a>: Includes S3 Transfer Acceleration<br />\n<a name=\"user-content-pci-rds\">**9**</a>: Includes RDS MySQL, Oracle, PostgreSQL, SQL Server, and MariaDB</br>\n<a name=\"user-content-pci-asg\">**10**</a>: Includes Auto-Scaling</br>\n<a name=\"user-content-pci-kinesis\">**11**</a>: Data Analytics, Streams, Video Streams and Firehose</br>\n<a name=\"user-content-eks-cli\">**12**</a>: Kubernetes uses a custom CLI for Pod/Service management called kubectl. AWS CLI only handles Kubernetes Master concerns</br>\n<a name=\"user-content-pci-iot\">**13**</a>: IoT Core (includes Device Management) and Greengrass</br>\n<a name=\"user-content-pci-elasticache\">**14**</a>: ElastiCache for Redis only</br>\n<a name=\"user-content-pci-snowball\">**15**</a>: Snowball and Snowball Edge</br>\n\n\n### Compliance\n\n-\tMany applications have strict requirements around reliability, security, or data privacy. The [AWS Compliance](https://aws.amazon.com/compliance/) page has details about AWS’s certifications, which include **PCI DSS Level 1**, **SOC 1,2, and 3**, **HIPAA**, and **ISO 9001**.\n-\tSecurity in the cloud is a complex topic, based on a [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/), where some elements of compliance are provided by AWS, and some are provided by your company.\n-\tSeveral third-party vendors offer assistance with compliance, security, and auditing on AWS. If you have substantial needs in these areas, assistance is a good idea.\n-\tFrom inside **China**, AWS services outside China [are generally accessible](https://en.greatfire.org/aws.amazon.com), though there are at times breakages in service. There are also AWS services [inside China](https://www.amazonaws.cn/en/).\n\n### Getting Help and Support\n\n-\t**Forums:** For many problems, it’s worth searching or asking for help in the [discussion forums](https://forums.aws.amazon.com/index.jspa) to see if it’s a known issue.\n-\t**Premium support:** AWS offers several levels of [premium support](https://aws.amazon.com/premiumsupport/).\n\t-\tThe first tier, called \"Developer support\" lets you file support tickets with 12 to 24 hour turnaround time, it starts at $29 but once your monthly spend reaches around $1000 it changes to a 3% surcharge on your bill.\n\t-\tThe higher-level support services are quite expensive — and increase your bill by up to 10%. Many large and effective companies never pay for this level of support. They are usually more helpful for midsize or larger companies needing rapid turnaround on deeper or more perplexing problems.\n\t-\tKeep in mind, a flexible architecture can reduce need for support. You shouldn’t be relying on AWS to solve your problems often. For example, if you can easily re-provision a new server, it may not be urgent to solve a rare kernel-level issue unique to one EC2 instance. If your EBS volumes have recent snapshots, you may be able to restore a volume before support can rectify the issue with the old volume. If your services have an issue in one availability zone, you should in any case be able to rely on a redundant zone or migrate services to another zone.\n\t-\tLarger customers also get access to AWS Enterprise support, with dedicated technical account managers (TAMs) and shorter response time SLAs.\n\t-\tThere is definitely some controversy about how useful the paid support is. The support staff don’t always seem to have the information and authority to solve the problems that are brought to their attention. Often your ability to have a problem solved may depend on your relationship with your account rep.\n-\t**Account manager:** If you are at significant levels of spend (thousands of US dollars plus per month), you may be assigned (or may wish to ask for) a dedicated account manager.\n\t-\tThese are a great resource, even if you’re not paying for premium support. Build a good relationship with them and make use of them, for questions, problems, and guidance.\n\t-\tAssign a single point of contact on your company’s side, to avoid confusing or overwhelming them.\n-\t**Contact:** The main web contact point for AWS is [here](https://aws.amazon.com/contact-us/). Many technical requests can be made via these channels.\n-\t**Consulting and managed services:** For more hands-on assistance, AWS has established relationships with many [consulting partners](https://aws.amazon.com/partners/consulting/) and [managed service partners](https://aws.amazon.com/partners/msp/). The big consultants won’t be cheap, but depending on your needs, may save you costs long term by helping you set up your architecture more effectively, or offering specific expertise, e.g. security. Managed service providers provide longer-term full-service management of cloud resources.\n-\t**AWS Professional Services:** AWS provides [consulting services](https://aws.amazon.com/professional-services/) alone or in combination with partners.\n\n### Restrictions and Other Notes\n\n-\t🔸Lots of resources in Amazon have [**limits**](http://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html) on them. This is actually helpful, so you don’t incur large costs accidentally. You have to request that quotas be increased by opening support tickets. Some limits are easy to raise, and some are not. (Some of these are noted in sections below.) Additionally, not all service limits are published.\n\t- **Obtaining Current Limits and Usage:** Limit information for a service may be available from the service API, Trusted Advisor, both or neither (in which case you'll need to contact Support). [This page](http://awslimitchecker.readthedocs.io/en/latest/limits.html) from the awslimitchecker tool's documentation provides a nice summary of available retrieval options for each limit. The [tool](https://github.com/jantman/awslimitchecker) itself is also valuable for automating limit checks.\n-\t🔸[**AWS terms of service**](https://aws.amazon.com/service-terms/) are extensive. Much is expected boilerplate, but it does contain important notes and restrictions on each service. In particular, there are restrictions against using many AWS services in **safety-critical systems**. (Those appreciative of legal humor may wish to review [clause 42.10](https://www.theguardian.com/technology/2016/feb/11/amazon-terms-of-service-zombie-apocalypse).)\n\n### Related Topics\n\n-\t[OpenStack](https://www.openstack.org/) is a private cloud alternative to AWS used by large companies that wish to avoid public cloud offerings.\n\nLearning and Career Development\n-------------------------------\n\n### Certifications\n\n-\t**Certifications:** AWS offers [**certifications**](https://aws.amazon.com/certification/) for IT professionals who want to demonstrate their knowledge.\n  -\t[Certified Cloud Practitioner](https://aws.amazon.com/certification/certified-cloud-practitioner/)\n  -\t[Certified Solutions Architect Associate](https://aws.amazon.com/certification/certified-solutions-architect-associate/)\n  -\t[Certified Developer Associate](https://aws.amazon.com/certification/certified-developer-associate/)\n  -\t[Certified SysOps Administrator Associate](https://aws.amazon.com/certification/certified-sysops-admin-associate/)\n  -\t[Certified Solutions Architect Professional](https://aws.amazon.com/certification/certified-solutions-architect-professional/)\n  -\t[Certified DevOps Engineer Professional](https://aws.amazon.com/certification/certified-devops-engineer-professional/)\n  - [Certified Security – Specialty](https://aws.amazon.com/certification/certified-security-specialty/)\n  - [Certified Advanced Networking – Specialty](https://aws.amazon.com/certification/certified-advanced-networking-specialty/)\n  - [Certified Machine Learning – Specialty](https://aws.amazon.com/certification/certified-machine-learning-specialty/)\n  - [Certified Data Analytics – Specialty](https://aws.amazon.com/certification/certified-data-analytics-specialty/)\n  - [Certified Database – Specialty](https://aws.amazon.com/certification/certified-database-specialty/)\n\nAssociate level certifications were once required as pre-requisites to taking the Professional examinations - this is no longer the case.\n\n-\t**Getting certified:** If you’re interested in studying for and getting certifications, [this practical overview](https://gist.github.com/leonardofed/bbf6459ad154ad5215d354f3825435dc) tells you a lot of what you need to know. The official page is [here](https://aws.amazon.com/training/) and there is an [FAQ](https://aws.amazon.com/certification/faqs/).\n-\t**Training for certifications:** Training is offered by AWS themselves (mainly instructor-led and on-site) and various third-party companies (usually as video-based training) such as [A Cloud Guru](https://acloud.guru/aws-cloud-training), [CloudAcademy](https://cloudacademy.com/library/amazon-web-services/) and [Linux Academy](https://linuxacademy.com/library/topics/AWS/type/Course/).\n-\t**Do you need a certification?** Especially in consulting companies or when working in key tech roles in large non-tech companies, certifications are important credentials. In others, including in many tech companies and startups, certifications are not common or considered necessary. (In fact, fairly or not, some Silicon Valley hiring managers and engineers see them as a “negative” signal on a resume.)\n\nCertifications are required to access certificate lounges at official AWS events such as [Summits](https://aws.amazon.com/events/summits/) and [re:Invent](https://reinvent.awsevents.com). Lounges typically provide power charging points, seats and relatively better coffee.\n\nManaging AWS\n------------\n\n### Managing Infrastructure State and Change\n\nA great challenge in using AWS to build complex systems (and with DevOps in general) is to manage infrastructure state effectively over time. In general, this boils down to three broad goals for the state of your infrastructure:\n\n-\t**Visibility**: Do you know the state of your infrastructure (what services you are using, and exactly how)? Do you also know when you — and anyone on your team — make changes? Can you detect misconfigurations, problems, and incidents with your service?\n-\t**Automation**: Can you reconfigure your infrastructure to reproduce past configurations or scale up existing ones without a lot of extra manual work, or requiring knowledge that’s only in someone’s head? Can you respond to incidents easily or automatically?\n-\t**Flexibility**: Can you improve your configurations and scale up in new ways without significant effort? Can you add more complexity using the same tools? Do you share, review, and improve your configurations within your team?\n\nMuch of what we discuss below is really about how to improve the answers to these questions.\n\nThere are several approaches to deploying infrastructure with AWS, from the console to complex automation tools, to third-party services, all of which attempt to help achieve visibility, automation, and flexibility.\n\n### AWS Configuration Management\n\nThe first way most people experiment with AWS is via its web interface, the AWS Console. But using the Console is a highly manual process, and often works against automation or flexibility.\n\nSo if you’re not going to manage your AWS configurations manually, what should you do? Sadly, there are no simple, universal answers — each approach has pros and cons, and the approaches taken by different companies vary widely, and include directly using APIs (and building tooling on top yourself), using command-line tools, and using third-party tools and services.\n\n### AWS Console\n\n-\tThe [AWS Console](https://aws.amazon.com/console/) lets you control much (but not all) functionality of AWS via a web interface.\n-\tIdeally, you should only use the AWS Console in a few specific situations:\n\t-\tIt’s great for read-only usage. If you’re trying to understand the state of your system, logging in and browsing it is very helpful.\n\t-\tIt is also reasonably workable for very small systems and teams (for example, one engineer setting up one server that doesn’t change often).\n\t-\tIt can be useful for operations you’re only going to do rarely, like less than once a month (for example, a one-time VPC setup you probably won’t revisit for a year). In this case using the console can be the simplest approach.\n-\t❗**Think before you use the console:** The AWS Console is convenient, but also the enemy of automation, reproducibility, and team communication. If you’re likely to be making the same change multiple times, avoid the console. Favor some sort of automation, or at least have a path toward automation, as discussed next. Not only does using the console preclude automation, which wastes time later, but it prevents documentation, clarity, and standardization around processes for yourself and your team.\n\n### Command-Line tools\n\n-\tThe [**aws command-line interface**](https://aws.amazon.com/cli/) (CLI), used via the **aws** command, is the most basic way to save and automate AWS operations.\n-\tDon’t underestimate its power. It also has the advantage of being well-maintained — it covers a large proportion of all AWS services, and is up to date.\n-\tIn general, whenever you can, prefer the command line to the AWS Console for performing operations.\n-\t🔹Even in the absence of fancier tools, you can **write simple Bash scripts** that invoke *aws* with specific arguments, and check these into Git. This is a primitive but effective way to document operations you’ve performed. It improves automation, allows code review and sharing on a team, and gives others a starting point for future work.\n-\t🔹For use that is primarily interactive (not scripted), consider instead using the [**aws-shell**](https://github.com/awslabs/aws-shell) tool from AWS. It is easier to use, with auto-completion and a colorful UI, but still works on the command line. If you’re using [SAWS](https://github.com/donnemartin/saws), a previous version of the program, [you should migrate to aws-shell](https://github.com/donnemartin/saws/issues/68#issuecomment-240067034).\n\n### APIs and SDKs\n\n-\t**SDKs** for using AWS APIs are available in most major languages, with [Go](https://github.com/aws/aws-sdk-go), [iOS](https://github.com/aws/aws-sdk-ios), [Java](https://github.com/aws/aws-sdk-java), [JavaScript](https://github.com/aws/aws-sdk-js), [Python](https://github.com/boto/boto3), [Ruby](https://github.com/aws/aws-sdk-ruby), and [PHP](https://github.com/aws/aws-sdk-php) being most heavily used. AWS maintains [a short list](https://aws.amazon.com/tools/#sdk), but the [awesome-aws list](https://github.com/donnemartin/awesome-aws#sdks-and-samples) is the most comprehensive and current. Note [support for C++](https://github.com/donnemartin/awesome-aws#c-sdk) is [still new](https://aws.amazon.com/blogs/aws/introducing-the-aws-sdk-for-c/).\n-\t**Retry logic:** An important aspect to consider whenever using SDKs is error handling; under heavy use, a wide variety of failures, from programming errors to throttling to AWS-related outages or failures, can be expected to occur. SDKs typically implement [**exponential backoff**](https://docs.aws.amazon.com/general/latest/gr/api-retries.html) to address this, but this may need to be understood and adjusted over time for some applications. For example, it is often helpful to alert on some error codes and not on others.\n-\t❗Don’t use APIs directly. Although AWS documentation includes lots of API details, it’s better to use the SDKs for your preferred language to access APIs. SDKs are more mature, robust, and well-maintained than something you’d write yourself.\n\n### Boto\n\n-\tA good way to automate operations in a custom way is [**Boto3**](https://github.com/boto/boto3), also known as the [Amazon SDK for Python](http://aws.amazon.com/sdk-for-python/). [**Boto2**](https://github.com/boto/boto), the previous version of this library, has been in wide use for years, but now there is a newer version with official support from Amazon, so prefer Boto3 for new projects.\n-\tBoto3 contains a variety of APIs that operate at either a high level or a low level, here some explanation of both:\n\t-\tThe low level APIs (Client APIs) are mapped to AWS Cloud service-specific APIs, and all service operations are supported by clients. Clients are generated from a JSON service definition file.\n\t-\tThe high level option, Resource APIs, allows you to avoid calling the network at the low level and instead provide an object-oriented way to interact with AWS Cloud services.\n-\tBoto3 has a lot of helpful [**features**](https://boto3.readthedocs.io/en/latest/guide/index.html#general-feature-guides) like *waiters*, which provide a structure that allows for code to wait for changes to occur in the cloud, for example, when you are creating an EC2 instance and need wait until the instance is running in order to perform another task.\n-\tIf you find yourself writing a Bash script with more than one or two CLI commands, you’re probably doing it wrong. Stop, and consider writing a Boto script instead. This has the advantages that you can:\n\t-\tCheck return codes easily so success of each step depends on success of past steps.\n\t-\tGrab interesting bits of data from responses, like instance ids or DNS names.\n\t-\tAdd useful environment information (for example, tag your instances with git revisions, or inject the latest build identifier into your initialization script).\n\n[Back to top :arrow_up:](#table-of-contents)\n### General Visibility\n\n-\t🔹[**Tagging resources**](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) is an essential practice, especially as organizations grow, to better understand your resource usage. For example, through automation or convention, you can add tags:\n\t-\tFor the org or developer that “owns” that resource\n\t-\tFor the product that resource supports\n\t-\tTo label lifecycles, such as temporary resources or one that should be deprovisioned in the future\n\t-\tTo distinguish production-critical infrastructure (e.g. serving systems vs backend pipelines)\n\t-\tTo distinguish resources with special security or compliance requirements\n\t-\tTo (once enabled) [allocate cost](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html). Note that cost allocation tags only apply on a forward-looking basis; you can't retroactively apply them to items already billed.\n\t-\tFor many years, there was a notorious 10 tag limit per resource, which could not be raised and caused many companies significant pain. As of 2016, this was [raised](https://aws.amazon.com/blogs/security/now-organize-your-aws-resources-by-using-up-to-50-tags-per-resource/) to 50 tags per resource.\n\t-\t🔹In 2017, AWS introduced the ability to [enforce tagging](https://aws.amazon.com/blogs/aws/new-tag-ec2-instances-ebs-volumes-on-creation/) on instance and volume creation, deprecating portions of third party tools such as [Cloud Custodian](https://github.com/capitalone/cloud-custodian).\n\t-\t🔸 Tags are case sensitive; 'environment' and 'Environment' are two different tags. Automation in setting tags is likely the only sensible option at significant scale.\n\t-\t🔸 There is a bug in the ASG console where spaces after tag names are preserved. So if you type \"Name \" with a space at the end you will not get the expected behavior. This is probably true in other locations and SDKs also. Be sure you do not add trailing spaces to tag keys unless you really mean it. (As of Jul 2018)\n\t-\t🔸 When resources are shared across the org, tags are not shared with it. For example, sharing Transit Gateway or AMIs will show the correct tags in the account that created these resources but not in the accounts where these resources were shared.\n\nManaging Servers and Applications\n---------------------------------\n\n[Back to top :arrow_up:](#table-of-contents)\n### AWS vs Server Configuration\n\nThis guide is about AWS, not DevOps or server configuration management in general. But before getting into AWS in detail, it’s worth noting that in addition to the configuration management for your AWS resources, there is the long-standing problem of configuration management for servers themselves.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Philosophy\n\n-\tHeroku’s [**Twelve-Factor App**](http://12factor.net/) principles list some established general best practices for deploying applications.\n-\t**Pets vs cattle:** Treat servers [like cattle, not pets](https://www.engineyard.com/blog/pets-vs-cattle). That is, design systems so infrastructure is disposable. It should be minimally worrisome if a server is unexpectedly destroyed.\n-\tThe concept of [**immutable infrastructure**](http://radar.oreilly.com/2015/06/an-introduction-to-immutable-infrastructure.html) is an extension of this idea.\n-\tMinimize application state on EC2 instances. In general, instances should be able to be killed or die unexpectedly with minimal impact. State that is in your application should quickly move to RDS, S3, DynamoDB, EFS, or other data stores not on that instance. EBS is also an option, though it generally should not be the bootable volume, and EBS will require manual or automated re-mounting.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Server Configuration Management\n\n-\tThere is a [large set](https://en.wikipedia.org/wiki/Comparison_of_open-source_configuration_management_software) of open source tools for managing configuration of server instances.\n-\tThese are generally not dependent on any particular cloud infrastructure, and work with any variety of Linux (or in many cases, a variety of operating systems).\n-\tLeading configuration management tools are [Puppet](https://github.com/puppetlabs/puppet), [Chef](https://github.com/chef/chef), [Ansible](https://github.com/ansible/ansible), and [Saltstack](https://github.com/saltstack/salt). These aren’t the focus of this guide, but we may mention them as they relate to AWS.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Containers and AWS\n\n-\t[Docker](http://blog.scottlowe.org/2014/03/11/a-quick-introduction-to-docker/) and the containerization trend are changing the way many servers and services are deployed in general.\n-\tContainers are designed as a way to package up your application(s) and all of their dependencies in a known way. When you build a container, you are including every library or binary your application needs, outside of the kernel. A big advantage of this approach is that it’s easy to test and validate a container locally without worrying about some difference between your computer and the servers you deploy on.\n-\tA consequence of this is that you need fewer AMIs and boot scripts; for most deployments, the only boot script you need is a template that fetches an exported docker image and runs it.\n-\tCompanies that are embracing [microservice architectures](http://martinfowler.com/articles/microservices.html) will often turn to container-based deployments.\n-\tAWS launched [ECS](https://aws.amazon.com/ecs/) as a service to manage clusters via Docker in late 2014, though many people still deploy Docker directly themselves. See the [ECS section](#ecs) for more details.\n-\tAWS launched [EKS](https://aws.amazon.com/eks/) as a service to manage Kubernetes Clusters mid 2018, though many people still deploy ECS or use Docker directly themselves. See the [EKS section](#eks) for more details.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Visibility\n\n-\tStore and track instance metadata (such as instance id, availability zone, etc.) and deployment info (application build id, Git revision, etc.) in your logs or reports. The [**instance metadata service**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) can help collect some of the AWS data you’ll need.\n-\t**Use log management services:** Be sure to set up a way to view and manage logs externally from servers.\n\t-\tCloud-based services such as [Sumo Logic](https://www.sumologic.com/), [Splunk Cloud](http://www.splunk.com/en_us/cloud.html), [Scalyr](https://www.scalyr.com/), [LogDNA](https://www.logdna.com/), and [Loggly](https://www.loggly.com/) are the easiest to set up and use (and also the most expensive, which may be a factor depending on how much log data you have).\n\t-\tMajor open source alternatives include [Elasticsearch](https://github.com/elastic/elasticsearch), [Logstash](https://github.com/elastic/logstash), and [Kibana](https://github.com/elastic/kibana) (the “[Elastic Stack](https://www.elastic.co/webinars/introduction-elk-stack)”) and [Graylog](https://www.graylog.org/).\n\t-\tIf you can afford it (you have little data or lots of money) and don’t have special needs, it makes sense to use hosted services whenever possible, since setting up your own scalable log processing systems is notoriously time consuming.\n-\t**Track and graph metrics:** The AWS Console can show you simple graphs from CloudWatch, you typically will want to track and graph many kinds of metrics, from CloudWatch and your applications. Collect and export helpful metrics everywhere you can (and as long as volume is manageable enough you can afford it).\n\t-\tServices like [Librato](https://www.librato.com/), [KeenIO](https://keen.io/), and [Datadog](https://www.datadoghq.com/) have fancier features or better user interfaces that can save a lot of time. (A more detailed comparison is [here](http://blog.takipi.com/production-tools-guide/visualization-and-metrics/).)\n\t-\tUse [Prometheus](https://prometheus.io) or [Graphite](https://github.com/graphite-project/graphite-web) as timeseries databases for your metrics (both are open source).\n\t-\t[Grafana](https://github.com/grafana/grafana) can visualize with dashboards the stored metrics of both timeseries databases (also open source).\n\n[Back to top :arrow_up:](#table-of-contents)\n### Tips for Managing Servers\n\n-\t❗**Timezone settings on servers**: unless *absolutely necessary*, always **set the timezone on servers to [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time)** (see instructions for your distribution, such as [Ubuntu](https://www.digitalocean.com/community/tutorials/how-to-set-up-timezone-and-ntp-synchronization-on-ubuntu-14-04-quickstart), [CentOS](https://www.vultr.com/docs/setup-timezone-and-ntp-on-centos-6) or [Amazon](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html) Linux). Numerous distributed systems rely on time for synchronization and coordination and UTC [provides](https://blog.serverdensity.com/set-your-server-timezone-to-utc/) the universal reference plane: it is not subject to  daylight savings changes and adjustments in local time. It will also save you a lot of headache debugging [elusive timezone issues](http://yellerapp.com/posts/2015-01-12-the-worst-server-setup-you-can-make.html) and provide coherent timeline of events in your logging and audit systems.\n-\t**NTP and accurate time:** If you are not using Amazon Linux (which comes preconfigured), you should confirm your servers [configure NTP correctly](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html#configure_ntp), to avoid insidious time drift (which can then cause all sorts of issues, from breaking API calls to misleading logs). This should be part of your automatic configuration for every server. If time has already drifted substantially (generally >1000 seconds), remember NTP won’t shift it back, so you may need to remediate manually (for example, [like this](http://askubuntu.com/questions/254826/how-to-force-a-clock-update-using-ntp) on Ubuntu).\n-\t**Testing immutable infrastructure:** If you want to be proactive about testing your service’s ability to cope with instance termination or failure, it can be helpful to introduce random instance termination during business hours, which will expose any such issues at a time when engineers are available to identify and fix them. Netflix’s [Simian Army](https://github.com/Netflix/SimianArmy) (specifically, [Chaos Monkey](https://github.com/Netflix/SimianArmy/wiki/Chaos-Monkey)) is a popular tool for this. Alternatively, [chaos-lambda](https://github.com/bbc/chaos-lambda) by the BBC is a lightweight option which runs on AWS [Lambda](#lambda).\n\nSecurity and IAM\n----------------\n\nWe cover security basics first, since configuring user accounts is something you usually have to do early on when setting up your system.\n\n### Security and IAM Basics\n\n-\t📒 IAM [Homepage](https://aws.amazon.com/iam/) ∙ [User guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) ∙ [FAQ](https://aws.amazon.com/iam/faqs/)\n-\tThe [AWS Security Blog](https://blogs.aws.amazon.com/security) is one of the best sources of news and information on AWS security.\n-\t**IAM** is the service you use to manage accounts and permissioning for AWS.\n-\tManaging security and access control with AWS is critical, so every AWS administrator needs to use and understand IAM, at least at a basic level.\n-\t[IAM identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html) include users (people or services that are using AWS), groups (containers for sets of users and their permissions), and roles (containers for permissions assigned to AWS service instances). [Permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_permissions.html) for these identities are governed by [policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) You can use AWS pre-defined policies or custom policies that you create.\n-\tIAM manages various kinds of authentication, for both users and for software services that may need to authenticate with AWS, including:\n\t-\t[**Passwords**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords.html) to log into the console. These are a username and password for real users.\n\t-\t[**Access keys**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html), which you may use with command-line tools. These are two strings, one the “id”, which is an upper-case alphabetic string of the form 'AXXXXXXXXXXXXXXXXXXX', and the other is the secret, which is a 40-character mixed-case base64-style string. These are often set up for services, not just users.\n\t\t-\t📜 Access keys that start with AKIA are normal keys. Access keys that start with ASIA are session/temporary keys from STS, and will require an additional \"SessionToken\" parameter to be sent along with the id and secret. See the documentation for [a complete list of access key prefixes](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-prefixes).\n\t-\t[**Multi-factor authentication (MFA)**](https://aws.amazon.com/iam/details/mfa/), which is the highly recommended practice of using a keychain fob or smartphone app as a second layer of protection for user authentication.\n-\tIAM allows complex and fine-grained control of permissions, dividing users into groups, assigning permissions to roles, and so on. There is a [policy language](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) that can be used to customize security policies in a fine-grained way.\n\t-\tAn excellent high level overview of IAM policy concepts lives at [IAM Policies In A Nutshell](http://start.jcolemorrison.com/aws-iam-policies-in-a-nutshell/).\n\t-\t🔸The policy language has a complex and error-prone JSON syntax that’s quite confusing, so unless you are an expert, it is wise to base yours off trusted examples or AWS’ own pre-defined [managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html).\n-\tAt the beginning, IAM policy may be very simple, but for large systems, it will grow in complexity, and need to be managed with care.\n\t-\t🔹Make sure one person (perhaps with a backup) in your organization is formally assigned ownership of managing IAM policies, make sure every administrator works with that person to have changes reviewed. This goes a long way to avoiding accidental and serious misconfigurations.\n-\tIt is best to give each user or service the minimum privileges needed to perform their duties. This is the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege), one of the foundations of good security. Organize all IAM users and groups according to levels of access they need.\n-\tIAM has the [permission hierarchy](http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) of:\n\t1. Explicit deny: The most restrictive policy wins.\n\t2. Explicit allow: Access permissions to any resource has to be explicitly given.\n\t3. Implicit deny: All permissions are implicitly denied by default.\n-\tYou can test policy permissions via the AWS IAM [policy simulator tool](https://policysim.aws.amazon.com/home/index.jsp). This is particularly useful if you write custom policies.\n\n\n[Back to top :arrow_up:](#table-of-contents)\n### Security and IAM Tips\n\n-\t🔹Use IAM to create individual user accounts and **use IAM accounts for all users from the beginning**. This is slightly more work, but not that much.\n\t-\tThat way, you define different users, and groups with different levels of privilege (if you want, choose from Amazon’s default suggestions, of administrator, power user, etc.).\n\t-\tThis allows credential revocation, which is critical in some situations. If an employee leaves, or a key is compromised, you can revoke credentials with little effort.\n\t-\tYou can set up [Active Directory federation](https://blogs.aws.amazon.com/security/post/Tx71TWXXJ3UI14/Enabling-Federation-to-AWS-using-Windows-Active-Directory-ADFS-and-SAML-2-0) to use organizational accounts in AWS.\n-\t❗**Enable [MFA](https://aws.amazon.com/iam/details/mfa/)** on your account.\n\t-\tYou should always use MFA, and the sooner the better — enabling it when you already have many users is extra work.\n\t-\tUnfortunately it can’t be enforced in software, so an administrative policy has to be established.\n\t-\tMost users can use the Google Authenticator app (on [iOS](https://itunes.apple.com/us/app/google-authenticator/id388497605) or [Android](https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2)) to support two-factor authentication. For the root account, consider a hardware fob.\n- ❗Restrict use of significant IAM credentials as much as possible. Remember that in the cloud, loss of a highly capable IAM credential could essentially mean “game over,” for your deployment, your users, or your whole company.\n  -\t**Do NOT use the [Root User account](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html)** other than when you initially create your account.  Create custom IAM users and/or roles and use those for your applications instead.\n\t- Lock up access and use of the root credentials as much as possible. Ideally they should be effectively “offline.” For critical deployments, this means attached to an actual MFA device, physically secured and rarely used.\n-\t❗**Turn on CloudTrail:** One of the first things you should do is [enable CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-create-a-trail-using-the-console-first-time.html). Even if you are not a security hawk, there is little reason not to do this from the beginning, so you have data on what has been happening in your AWS account should you need that information. You’ll likely also want to set up a [log management service](#visibility) to search and access these logs.\n-\t🔹**Use IAM roles for EC2:** Rather than assign IAM users to applications like services and then sharing the sensitive credentials, [define and assign roles to EC2 instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) and have applications retrieve credentials from the [instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).\n-\tAssign IAM roles by realm — for example, to development, staging, and production. If you’re setting up a role, it should be tied to a specific realm so you have clean separation. This prevents, for example, a development instance from connecting to a production database.\n-\t**Best practices:** AWS’ [list of best practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) is worth reading in full up front.\n-\t**IAM Reference:** [This interactive reference for all IAM actions, effects, and resources](https://iam.cloudonaut.io/) is great to have open while writing new or trying to understand existing IAM policies.\n-\t**Multiple accounts:** Decide on whether you want to use multiple AWS accounts and [research](https://dab35129f0361dca3159-2fe04d8054667ffada6c4002813eccf0.ssl.cf1.rackcdn.com/downloads/pdfs/Rackspace%20Best%20Practices%20for%20AWS%20-%20Identity%20Managment%20-%20Billing%20-%20Auditing.pdf) how to organize access across them. Factors to consider:\n\t-\tNumber of users\n\t-\tImportance of isolation\n\t\t-\tResource Limits\n\t\t-\tPermission granularity\n\t\t-\tSecurity\n\t\t-\tAPI Limits\n\t-\tRegulatory issues\n\t-\tWorkload\n\t-\tSize of infrastructure\n\t-\tCost of multi-account “overhead”: Internal AWS service management tools may need to be custom built or adapted.\n\t-\t🔹It can help to use separate AWS accounts for independent parts of your infrastructure if you expect a high rate of AWS API calls, since AWS [throttles calls](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html#api-request-rate) at the AWS account level.\n-\t[**Inspector**](https://aws.amazon.com/inspector/) is an automated security assessment service from AWS that helps identify common security risks. This allows validation that you adhere to certain security practices and may help with compliance.\n-\t[**Trusted Advisor**](https://aws.amazon.com/blogs/aws/trusted-advisor-console-basic/) addresses a variety of best practices, but also offers some basic security checks around IAM usage, security group configurations, and MFA. At paid support tiers, Trusted Advisor exposes additional checks around other areas, such as reserved instance optimization.\n-\t**Use KMS for managing keys**: AWS offers [KMS](#kms) for securely managing encryption keys, which is usually a far better option than handling key security yourself. See [below](#kms).\n-\t[**AWS WAF**](https://aws.amazon.com/waf) is a web application firewall to help you protect your applications from common attack patterns.\n-\t**Security auditing:**\n\t-\t[Security Monkey](https://github.com/Netflix/security_monkey) is an open source tool that is designed to assist with security audits.\n\t-\t[Scout2](https://github.com/nccgroup/Scout2) is an open source tool that uses AWS APIs to assess an environment’s security posture. Scout2 is stable and actively maintained.\n\t-\t🔹**Export and audit security settings:** You can audit security policies simply by exporting settings using AWS APIs, e.g. using a Boto script like [SecConfig.py](https://gist.github.com/jlevy/cce1b44fc24f94599d0a4b3e613cc15d) (from [this 2013 talk](http://www.slideshare.net/AmazonWebServices/intrusion-detection-in-the-cloud-sec402-aws-reinvent-2013)) and then reviewing and monitoring changes manually or automatically.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Security and IAM Gotchas and Limitations\n\n-\t❗**Don’t share user credentials:** It’s remarkably common for first-time AWS users to create one account and one set of credentials (access key or password), and then use them for a while, sharing among engineers and others within a company. This is easy. But *don’t do this*. This is an insecure practice for many reasons, but in particular, if you do, you will have reduced ability to revoke credentials on a per-user or per-service basis (for example, if an employee leaves or a key is compromised), which can lead to serious complications.\n-\t❗**Instance metadata throttling:** The [instance metadata service](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) has rate limiting on API calls. If you deploy IAM roles widely (as you should!) and have lots of services, you may hit global account limits easily.\n\t-\tOne solution is to have code or scripts cache and reuse the credentials locally for a short period (say 2 minutes). For example, they can be put into the ~/.aws/credentials file but must also be refreshed automatically.\n\t-\tBut be careful not to cache credentials for too long, as [they expire](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials). (Note the other [dynamic metadata](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#dynamic-data-categories) also changes over time and should not be cached a long time, either.)\n-\t🔸Some IAM operations are slower than other API calls (many seconds), since AWS needs to propagate these globally across regions.\n-\t❗The uptime of IAM’s API has historically been lower than that of the instance metadata API. Be wary of incorporating a dependency on IAM’s API into critical paths or subsystems — for example, if you validate a user’s IAM group membership when they log into an instance and aren’t careful about precaching group membership or maintaining a back door, you might end up locking users out altogether when the API isn’t available.\n-\t❗**Don't check in AWS credentials or secrets to a git repository.** There are bots that scan GitHub looking for credentials. Use scripts or tools, such as [git-secrets](https://github.com/awslabs/git-secrets) to prevent anyone on your team from checking in sensitive information to your git repositories.\n\nS3\n--\n\n### S3 Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/s3/) ∙ [Developer guide](https://docs.aws.amazon.com/AmazonS3/latest/dev/Welcome.html) ∙ [FAQ](https://aws.amazon.com/s3/faqs/) ∙ [Pricing](https://aws.amazon.com/s3/pricing/)\n-\t**S3** (Simple Storage Service) is AWS’ standard cloud storage service, offering file (opaque “blob”) storage of arbitrary numbers of files of almost any size, from 0 to **5TB**. (Prior to [2011](https://aws.amazon.com/releasenotes/Amazon-S3/1917932037969964) the maximum size was 5 GB; larger sizes are now well supported via [multipart support](https://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html).)\n-\tItems, or **objects**, are placed into named **buckets** stored with names which are usually called **keys**. The main content is the **value**.\n-\tObjects are created, deleted, or updated. Large objects can be streamed, but you cannot modify parts of a value; you need to update the whole object. Partial data access can work via [S3 Select](https://aws.amazon.com/blogs/aws/s3-glacier-select/).\n-\tEvery object also has [**metadata**](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html), which includes arbitrary key-value pairs, and is used in a way similar to HTTP headers. Some metadata is system-defined, some are significant when serving HTTP content from buckets or CloudFront, and you can also define arbitrary metadata for your own use.\n-\t**S3 URIs:** Although often bucket and key names are provided in APIs individually, it’s also common practice to write an S3 location in the form 's3://bucket-name/path/to/key' (where the key here is 'path/to/key'). (You’ll also see 's3n://' and 's3a://' prefixes [in Hadoop systems](https://cwiki.apache.org/confluence/display/HADOOP2/AmazonS3).)\n-\t**S3 vs Glacier, EBS, and EFS:** AWS offers many storage services, and several besides S3 offer file-type abstractions. [Glacier](#glacier) is for cheaper and infrequently accessed archival storage. [EBS](#ebs), unlike S3, allows random access to file contents via a traditional filesystem, but can only be attached to one EC2 instance at a time. [EFS](#efs) is a network filesystem many instances can connect to, but at higher cost. See the [comparison table](#storage-durability-availability-and-price).\n\n[Back to top :arrow_up:](#table-of-contents)\n### S3 Tips\n\n-\tFor most practical purposes, you can consider S3 capacity unlimited, both in total size of files and number of objects. The number of objects in a bucket is essentially also unlimited. Customers routinely have millions of objects.\n-   ❗**Permissions:**\n    -   🔸If you're storing business data on Amazon S3, it’s important to manage permissions sensibly. In 2017 companies like [Dow Jones and Verizon](http://www.techrepublic.com/article/massive-amazon-s3-breaches-highlight-blind-spots-in-enterprise-race-to-the-cloud/) saw data breaches due to poorly-chosen S3 configuration for sensitive data. Fixing this later can be a difficult task if you have a lot of assets and internal users.\n    -   🔸There are 3 different ways to grant permissions to access Amazon S3 content in your buckets.\n        + **IAM policies** use the familiar [Identity and Access Management](#security-and-iam) permission scheme to control access to specific operations.\n        + **Bucket policies** grant or deny permissions to an entire bucket. You might use this when hosting a website in S3, to make the bucket publicly readable, or to restrict access to a bucket by IP address. Amazon's [sample bucket policies](http://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html) show a number of use cases where these policies come in handy.\n        + **[Access Control Lists](http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html)** (ACLs) can also be applied to every bucket and object stored in S3. ACLs grant additional permissions beyond those specified in IAM or bucket policies. ACLs can be used to grant access to another AWS user, or to predefined groups like the general public. This is powerful but can be dangerous, because you need to inspect every object to see who has access.\n    -   🔸AWS' [predefined access control groups](http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#specifying-grantee-predefined-groups) allow access that may not be what you'd expect from their names:\n        +   **\"All Users\", or \"Everyone\", grants permission to the general public**, not only to users defined in your own AWS account. If an object is available to All Users, then it can be retrieved with a simple HTTP request of the form `http://s3.amazonaws.com/bucket-name/filename`. No authorization or signature is required to access data in this category.\n        +   **\"Authenticated Users\" grants permissions to anyone with an AWS account**, again not limited to your own users. Because anyone can sign up for AWS, for all intents and purposes **this is also open to the general public**.\n        +   **\"Log Delivery\" group is used by AWS to write logs to buckets** and should be safe to enable on the buckets that need it.\n        +   A typical use case of this ACL is used in conjunction with the [requester pays](http://docs.aws.amazon.com/AmazonS3/latest/dev/RequesterPaysBuckets.html) functionality of S3.\n    -   ❗ Bucket permissions and object permissions are two different things and independent of each other. A private object in a public bucket can be seen when listing the bucket, but not downloaded. At the same time, a public object in a private bucket won't be seen because the bucket contents can't be listed, but can still be downloaded by anyone who knows its exact key. Users that don't have access to set bucket permissions can still make objects public if they have `s3:PutObjectAcl` or `s3:PutObjectVersionAcl` [permissions](http://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html).\n    -   🐥In August 2017, AWS added [AWS Config rules to ensure your S3 buckets are secure](https://aws.amazon.com/blogs/aws/aws-config-update-new-managed-rules-to-secure-s3-buckets/).\n        +    ❗These AWS Config rules only check the security of your bucket policy and bucket-level ACLs. You can still create object ACLs that grant additional permissions, including opening files to the whole world.\n    -   🔹Do create new buckets if you have different types of data with different sensitivity levels. This is much less error prone than complex permissions rules. For example, if data is for administrators only, like log data, put it in a new bucket that only administrators can access.\n    -   For more guidance, see:\n        +   [How to Secure an Amazon S3 Bucket](https://read.acloud.guru/how-to-secure-an-s3-bucket-7e2dbd34e81b)\n        +   [Deep dive into S3 access controls](https://labs.detectify.com/2017/07/13/a-deep-dive-into-aws-s3-access-controls-taking-full-control-over-your-assets/).\n        +   [How do S3 permissions work?](https://brandonwamboldt.ca/understanding-s3-permissions-1662/).\n-\t**Bucket naming:** Buckets are chosen from a global namespace (across all regions, even though S3 itself stores data in [whichever S3 region](https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) you select), so you’ll find many bucket names are already taken. Creating a bucket means taking ownership of the name until you delete it. Bucket names have [a few restrictions](https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html) on them.\n\t-\tBucket names can be used as part of the hostname when accessing the bucket or its contents, like `<bucket_name>.s3-us-east-1.amazonaws.com`, as long as the name is [DNS compliant](http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html).\n\t-\tA common practice is to use the company name acronym or abbreviation to prefix (or suffix, if you prefer DNS-style hierarchy) all bucket names (but please, don’t use a check on this as a security measure — this is highly insecure and easily circumvented!).\n\t-\t🔸Bucket names with '.' (periods) in them [can cause certificate mismatches](https://forums.aws.amazon.com/thread.jspa?threadID=169951) when used with SSL. Use '-' instead, since this then conforms with both SSL expectations and is DNS compliant.\n-\t**Versioning:** S3 has [optional versioning support](https://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectVersioning.html), so that all versions of objects are preserved on a bucket. This is mostly useful if you want an archive of changes or the ability to back out mistakes (caution: it lacks the featureset of full version control systems like Git).\n-\t**Durability:** Durability of S3 is extremely high, since internally it keeps several replicas. If you don’t delete it by accident, you can count on S3 not losing your data. (AWS offers the seemingly improbable durability rate of [99.999999999%](https://aws.amazon.com/s3/faqs/#How_durable_is_Amazon_S3), but this is a mathematical calculation based on independent failure rates and levels of replication — not a true probability estimate. Either way, S3 has had [a very good record](https://www.quora.com/Has-Amazon-S3-ever-lost-data-permanently) of durability.) Note this is *much* higher durability than EBS!\n-\t💸**S3 pricing** depends on [storage, requests, and transfer](https://aws.amazon.com/s3/pricing/).\n\t-\tFor transfer, putting data into AWS is free, but you’ll pay on the way out. Transfer from S3 to EC2 in the *same region* is free. Transfer to other regions or the Internet in general is not free.\n\t-\tDeletes are free.\n-\t**S3 Reduced Redundancy and Infrequent Access:** Most people use the Standard storage class in S3, but there are other storage classes with lower cost:\n\t-\t🔸[Reduced Redundancy Storage (RRS)](https://aws.amazon.com/s3/reduced-redundancy/) has been [effectively deprecated](https://www.lastweekinaws.com/blog/s3-reduced-redundancy-storage-is-dead/), and has lower durability (99.99%, so just four nines) than standard S3. Note that it no longer participates in S3 price reductions, so it offers worse redundancy for more money than standard S3. As a result, there's no reason to use it.\n\t-\t[Infrequent Access (IA)](https://aws.amazon.com/s3/storage-classes/#Infrequent_Access) lets you get cheaper storage in exchange for more expensive access. This is great for archives like logs you already processed, but might want to look at later. To get an idea of the cost savings when using Infrequent Access (IA), you can use this [S3 Infrequent Access Calculator](http://www.gulamshakir.com/apps/s3calc/index.html).\n\t-\t[S3 - Intelligent Tiering](https://aws.amazon.com/about-aws/whats-new/2018/11/s3-intelligent-tiering/) storage class is designed to optimize costs by automatically moving data to the most cost-effective access tier, without performance impact or operational overhead.\n\t-\t[S3 - One Zone - IA](https://aws.amazon.com/s3/storage-classes/#__) is for data that is accessed less frequently, but requires rapid access when needed. Unlike other S3 Storage Classes which store data in a minimum of three Availability Zones (AZs), S3 One Zone-IA stores data in a single AZ and costs 20% less than S3 Standard-IA.\n\t-\t[Glacier](#glacier) is a third alternative discussed as a separate product.\n\t-\tSee [the comparison table](#storage-durability-availability-and-price).\n-\t⏱**Performance:** Maximizing S3 performance means improving overall throughput in terms of bandwidth and number of operations per second.\n\t-\tS3 is highly scalable, so in principle you can get arbitrarily high throughput. (A good example of this is [S3DistCp](https://docs.aws.amazon.com/ElasticMapReduce/latest/ReleaseGuide/UsingEMR_s3distcp.html).)\n\t-\tBut usually you are constrained by the pipe between the source and S3 and/or the level of concurrency of operations.\n\t-\tThroughput is of course highest from within AWS to S3, and between EC2 instances and S3 buckets that are in the same region.\n\t-\tBandwidth from EC2 depends on instance type. See the “Network Performance” column at [ec2instances.info](http://www.ec2instances.info/).\n\t-\tThroughput of many objects is extremely high when data is accessed in a distributed way, from many EC2 instances. It’s possible to read or write objects from S3 from hundreds or thousands of instances at once.\n\t-\tHowever, throughput is very limited when objects accessed sequentially from a single instance. Individual operations take many milliseconds, and bandwidth to and from instances is limited.\n\t-\tTherefore, to perform large numbers of operations, it’s necessary to use multiple worker threads and connections on individual instances, and for larger jobs, multiple EC2 instances as well.\n\t-\t**Multi-part uploads:** For large objects you want to take advantage of the multi-part uploading capabilities (starting with minimum chunk sizes of 5 MB).\n\t-\t**Large downloads:** Also you can download chunks of a single large object in parallel by exploiting the HTTP GET range-header capability.\n\t-\t🔸**List pagination:** Listing contents happens at 1000 responses per request, so for buckets with many millions of objects listings will take time.\n\t-\t❗**Key prefixes:** Previously randomness in the beginning of key names was necessary in order to avoid hot spots, but that is [no longer necessary](https://aws.amazon.com/about-aws/whats-new/2018/07/amazon-s3-announces-increased-request-rate-performance/) as of July, 2018.\n\t-\tFor data outside AWS, [**DirectConnect**](https://aws.amazon.com/directconnect/) and [**S3 Transfer Acceleration**](https://aws.amazon.com/blogs/aws/aws-storage-update-amazon-s3-transfer-acceleration-larger-snowballs-in-more-regions/) can help. For S3 Transfer Acceleration, you [pay](https://aws.amazon.com/s3/pricing/) about the equivalent of 1-2 months of storage for the transfer in either direction for using nearer endpoints.\n-\t**Command-line applications:** There are a few ways to use S3 from the command line:\n\t-\tOriginally, [**s3cmd**](https://github.com/s3tools/s3cmd) was the best tool for the job. It’s still used heavily by many.\n\t-\tThe regular [**aws**](https://aws.amazon.com/cli/) command-line interface now supports S3 well, and is useful for most situations.\n\t-\t[**s4cmd**](https://github.com/bloomreach/s4cmd) is a replacement, with greater emphasis on performance via multi-threading, which is helpful for large files and large sets of files, and also offers Unix-like globbing support.\n-\t**GUI applications:** You may prefer a GUI, or wish to support GUI access for less technical users. Some options:\n\t-\tThe [AWS Console](https://aws.amazon.com/console/) does offer a graphical way to use S3. Use caution telling non-technical people to use it, however, since without tight permissions, it offers access to many other AWS features.\n\t-\t[Transmit](https://panic.com/transmit/) is a good option on macOS for most use cases.\n\t-\t[Cyberduck](https://cyberduck.io/) is a good option on macOS and Windows with support for multipart uploads, ACLs, versioning, lifecycle configuration, storage classes and server side encryption (SSE-S3 and SSE-KMS).\n-\t**S3 and CloudFront:** S3 is tightly integrated with the CloudFront CDN. See the CloudFront section for more information, as well as [S3 transfer acceleration](https://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html).\n-\t**Static website hosting:**\n\t-\tS3 has a [static website hosting option](http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html) that is simply a setting that enables configurable HTTP index and error pages and [HTTP redirect support](http://docs.aws.amazon.com/AmazonS3/latest/dev/how-to-page-redirect.html) to [public content](http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteAccessPermissionsReqd.html) in S3. It’s a simple way to host static assets or a fully static website.\n\t-\tConsider using CloudFront in front of most or all assets:\n\t\t-\tLike any CDN, CloudFront improves performance significantly.\n\t\t-\t🔸SSL is only supported on the built-in amazonaws.com domain for S3. S3 supports serving these sites through a [custom domain](http://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-custom-domain-walkthrough.html), but [not over SSL on a custom domain](http://stackoverflow.com/questions/11201316/how-to-configure-ssl-for-amazon-s3-bucket). However, [CloudFront allows you to serve a custom domain over https](http://docs.aws.amazon.com/acm/latest/userguide/gs-cf.html). Amazon provides free SNI SSL/TLS certificates via Amazon Certificate Manager. [SNI does not work on very outdated browsers/operating systems](https://en.wikipedia.org/wiki/Server_Name_Indication#Support). Alternatively, you can provide your own certificate to use on CloudFront to support all browsers/operating systems for a fee.\n\t\t-\t🔸If you are including resources across domains, such as fonts inside CSS files, you may need to [configure CORS](https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html) for the bucket serving those resources.\n\t\t-\tSince pretty much everything is moving to SSL nowadays, and you likely want control over the domain, you probably want to set up CloudFront with your own certificate in front of S3 (and to ignore the [AWS example on this](http://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-custom-domain-walkthrough.html) as it is non-SSL only).\n\t\t-\tThat said, if you do, you’ll need to think through invalidation or updates on CloudFront. You may wish to [include versions or hashes in filenames](https://abhishek-tiwari.com/CloudFront-design-patterns-and-best-practices) so invalidation is not necessary.\n-\t**Data lifecycles:**\n\t-\tWhen managing data, the understanding the lifecycle of the data is as important as understanding the data itself. When putting data into a bucket, think about its lifecycle — its end of life, not just its beginning.\n\t-\t🔹In general, data with different expiration policies should be stored under separate prefixes at the top level. For example, some voluminous logs might need to be deleted automatically monthly, while other data is critical and should never be deleted. Having the former in a separate bucket or at least a separate folder is wise.\n\t-\t🔸Thinking about this up front will save you pain. It’s very hard to clean up large collections of files created by many engineers with varying lifecycles and no coherent organization.\n\t-\tAlternatively you can set a lifecycle policy to archive old data to Glacier. [Be careful](https://alestic.com/2012/12/s3-glacier-costs/) with archiving large numbers of small objects to Glacier, since it may actually cost more.\n\t-\tThere is also a storage class called [**Infrequent Access**](https://aws.amazon.com/s3/storage-classes/#Infrequent_Access) that has the same durability as Standard S3, but is discounted per GB. It is suitable for objects that are infrequently accessed.\n-\t**Data consistency:** Understanding [data consistency](https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyModel) is critical for any use of S3 where there are multiple producers and consumers of data.\n\t-\tCreation and updates to individual objects in S3 are **atomic**, in that you’ll never upload a new object or change an object and have another client see only part half the change.\n\t- The uncertainty lies with *when* your clients and other clients see updates.\n\t-\t**New objects:** If you create a new object, you’ll be able to read it instantly, which is called **read-after-write consistency**.\n\t\t-\tWell, with the additional caveat that if you do a read on an object before it exists, then create it, [you get eventual consistency](https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyModel) (not read-after-write).\n\t\t-\tThis does not apply to any list operations; newly created objects are [not guaranteed to appear in a list operation right away](https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyModel)\n\t-\t**Updates to objects:** If you overwrite or delete an object, you’re only guaranteed **eventual consistency**, i.e. the change will happen but you have no guarantee of when.\n\t- 🔹For many use cases, treating S3 objects as **immutable** (i.e. deciding by convention they will be created or deleted but not updated) can greatly simplify the code that uses them, avoiding complex state management.\n\t-\t🔹Note that [until 2015](https://aws.amazon.com/about-aws/whats-new/2015/08/amazon-s3-introduces-new-usability-enhancements/), 'us-standard' region had had a weaker eventual consistency model, and the other (newer) regions were read-after-write. This was finally corrected — but watch for many old blogs mentioning this!\n\t-\t**Slow updates:** In practice, “eventual consistency” usually means within seconds, but expect rare cases of minutes or [hours](https://web.archive.org/web/20160324095125/http://www.stackdriver.com/eventual-consistency-really-eventual/).\n-\t**S3 as a filesystem:**\n\t-\tIn general S3’s APIs have inherent limitations that make S3 hard to use directly as a POSIX-style filesystem while still preserving S3’s own object format. For example, appending to a file requires rewriting, which cripples performance, and atomic rename of directories, mutual exclusion on opening files, and hardlinks are impossible.\n\t-\t[s3fs](https://github.com/s3fs-fuse/s3fs-fuse) is a FUSE filesystem that goes ahead and tries anyway, but it has performance limitations and surprises for these reasons.\n\t-\t[Riofs](https://github.com/skoobe/riofs) (C) and [Goofys](https://github.com/kahing/goofys) (Go) are more recent efforts that attempt adopt a different data storage format to address those issues, and so are likely improvements on s3fs.\n\t-\t[S3QL](https://github.com/s3ql/s3ql) ([discussion](https://news.ycombinator.com/item?id=10150684)) is a Python implementation that offers data de-duplication, snap-shotting, and encryption, but only one client at a time.\n\t-\t[ObjectiveFS](https://objectivefs.com/) ([discussion](https://news.ycombinator.com/item?id=10117506)) is a commercial solution that supports filesystem features and concurrent clients.\n-\tIf you are primarily using a VPC, consider setting up a [VPC Endpoint](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-endpoints.html) for S3 in order to allow your VPC-hosted resources to easily access it without the need for extra network configuration or hops.\n-\t**Cross-region replication:** S3 has [a feature](https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html) for replicating a bucket between one region and another. Note that S3 is already highly replicated within one region, so usually this isn’t necessary for durability, but it could be useful for compliance (geographically distributed data storage), lower latency, or as a strategy to reduce region-to-region bandwidth costs by mirroring heavily used data in a second region.\n-\t**IPv4 vs IPv6:** For a long time S3 only supported IPv4 at the default endpoint `https://BUCKET.s3.amazonaws.com`. However, [as of Aug 11, 2016](https://aws.amazon.com/blogs/aws/now-available-ipv6-support-for-amazon-s3/) it now supports both IPv4 & IPv6! To use both, you have to [enable dualstack](http://docs.aws.amazon.com/AmazonS3/latest/dev/dual-stack-endpoints.html) either in your preferred API client or by directly using this url scheme `https://BUCKET.s3.dualstack.REGION.amazonaws.com`. This extends to S3 Transfer Acceleration as well.\n-\t**S3 event notifications:** S3 can be configured to send an [SNS notification](https://aws.amazon.com/blogs/aws/introducing-the-amazon-simple-notification-service/), [SQS message](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Welcome.html), or [AWS Lambda function](http://docs.aws.amazon.com/lambda/latest/dg/welcome.html) on [bucket events](http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html).\n-   💸Limit your individual users (or IAM roles) to the minimal required S3 locations, and catalog the “approved” locations. Otherwise, S3 tends to become the dumping ground where people put data to random locations that are not cleaned up for years, costing you big bucks.\n- If a bucket is deleted in S3, it can take up to 10 hours before a bucket with the same name can be created again. ([discussion](https://forums.aws.amazon.com/thread.jspa?threadID=37532))\n\n[Back to top :arrow_up:](#table-of-contents)\n### S3 Gotchas and Limitations\n\n-   ❗S3 buckets sit outside the VPC and can be accessed from anywhere in the world if bucket policies are not set to deny it. Read the permissions section above carefully, there are countless cases of buckets exposed to the public.\n-\t🔸For many years, there was a notorious [**100-bucket limit**](https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_s3) per account, which could not be raised and caused many companies significant pain. As of 2015, you can [request increases](https://aws.amazon.com/about-aws/whats-new/2015/08/amazon-s3-introduces-new-usability-enhancements/). You can ask to increase the limit, but it will still be capped (generally below ~1000 per account).\n-\t🔸Be careful not to make implicit assumptions about transactionality or sequencing of updates to objects. Never assume that if you modify a sequence of objects, the clients will see the same modifications in the same sequence, or if you upload a whole bunch of files, that they will all appear at once to all clients.\n-\t🔸S3 has an [**SLA**](https://aws.amazon.com/s3/sla/) with 99.9% uptime. If you use S3 heavily, you’ll inevitably see occasional error accessing or storing data as disks or other infrastructure fail. Availability is usually restored in seconds or minutes. Although availability is not extremely high, as mentioned above, durability is excellent.\n-\t🔸After uploading, any change that you make to the object causes a full rewrite of the object, so avoid appending-like behavior with regular files.\n-\t🔸Eventual data consistency, as discussed above, can be surprising sometimes. If S3 suffers from internal replication issues, an object may be visible from a subset of the machines, depending on which S3 endpoint they hit. Those usually resolve within seconds; however, we’ve seen isolated cases when the issue lingered for 20-30 hours.\n-\t🔸**MD5s and multi-part uploads:** In S3, the [ETag header in S3](http://docs.aws.amazon.com/AmazonS3/latest/API/RESTCommonResponseHeaders.html) is a hash on the object. And in many cases, it is the MD5 hash. However, this [is not the case in general](http://stackoverflow.com/questions/12186993/what-is-the-algorithm-to-compute-the-amazon-s3-etag-for-a-file-larger-than-5gb) when you use multi-part uploads. One workaround is to compute MD5s yourself and put them in a custom header (such as is done by [s4cmd](https://github.com/bloomreach/s4cmd)).\n-\t🔸**Incomplete multi-part upload costs:** Incomplete multi-part uploads accrue [storage charges](http://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html#mpuploadpricing) even if the upload fails and no S3 object is created. [Amazon](http://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html#mpu-abort-incomplete-mpu-lifecycle-config) ([and](http://www.deplication.net/2016/06/aws-tip-save-s3-costs-with-abort.html) [others](https://www.sumologic.com/aws/s3/s3-cost-optimization/)) recommend using a lifecycle policy to clean up incomplete uploads and save on storage costs. Note that if you have many of these, it may be worth investigating whatever's failing regularly.\n-\t🔸**US Standard region:** Previously, the us-east-1 region (also known as the US Standard region) was replicated across coasts, which led to greater variability of latency. Effective Jun 19, 2015 this is [no longer the case](https://forums.aws.amazon.com/ann.jspa?annID=3112). All Amazon S3 regions now support read-after-write consistency. Amazon S3 also renamed the US Standard region to the US East (N. Virginia) region to be consistent with AWS regional naming conventions.\n- 🔸**S3 authentication versions and regions:** In newer regions, S3 [only supports the latest authentication](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version). If an S3 file operation using CLI or SDK doesn't work in one region, but works correctly in another region, make sure you are using the latest [authentication signature](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html).\n\n[Back to top :arrow_up:](#table-of-contents)\n### Storage Durability, Availability, and Price\n\nAs an illustration of comparative features and price, the table below gives S3 Standard, RRS, IA, in comparison with [Glacier](#glacier), [EBS](#ebs), [EFS](#efs), and EC2 d2.xlarge instance store using **Virginia region** as of **Sept 2017**.\n\n|                 | Durability (per year)  | Availability “designed” | Availability SLA | Storage (per TB per month)                                                                                               | GET or retrieve (per million) | Write or archive (per million) |\n|-----------------|------------------------|-------------------------|------------------|--------------------------------------------------------------------------------------------------------------------------|-------------------------------|--------------------------------|\n| **Glacier**     | Eleven 9s              | Sloooow                 | –                | $4                                                                                                                       | $50                           | $50                            |\n| **S3 IA**       | Eleven 9s              | 99.9%                   | **99%**          | $12.50                                                                                                                   | $1                            | $10                            |\n| ~~**S3 RRS**~~      | ~~**99.99%**~~             | ~~99.99%~~                  | ~~99.9%~~            | ~~$24 (first TB)~~                                                                                                                      | ~~$0.40~~                         | ~~$5~~                             |\n| **S3 Standard** | Eleven 9s              | 99.99%                  | 99.9%            | $23                                                                                                                     | $0.40                         | $5                             |\n| **EBS**         | **99.8%**              | Unstated                | 99.99%           | $25/$45/**$100**/$125+ ([sc1/st1/**gp2**/io1](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html)\\) |                               |                                |\n| **EFS**         | “High”                 | “High”                  | –                | $300                                                                                                                     |                               |                                |\n| **EC2 d2.xlarge instance store**  | Unstated | Unstated                | –                | $25.44                                                                                                                   | $0                            | $0                             |\n\nEspecially notable items are in **boldface**. Sources: [S3 pricing](https://aws.amazon.com/s3/pricing/), [S3 SLA](https://aws.amazon.com/s3/sla/), [S3 FAQ](https://aws.amazon.com/s3/faqs/), [RRS info](https://aws.amazon.com/s3/reduced-redundancy/) (note that this is considered deprecated), [Glacier pricing](https://aws.amazon.com/glacier/pricing/), [EBS availability and durability](https://aws.amazon.com/ebs/details/#Amazon_EBS_Availability_and_Durability), [EBS pricing](https://aws.amazon.com/ebs/pricing/), [EFS pricing](https://aws.amazon.com/efs/pricing/), [EC2 SLA](https://aws.amazon.com/ec2/sla/)\n\nEC2\n---\n\n### EC2 Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/ec2/) ∙ [Documentation](https://aws.amazon.com/documentation/ec2/) ∙ [FAQ](https://aws.amazon.com/ec2/faqs/) ∙ [Pricing](https://aws.amazon.com/ec2/pricing/) (see also [ec2instances.info](http://www.ec2instances.info/)\\)\n-\t**EC2** (Elastic Compute Cloud) is AWS’ offering of the most fundamental piece of cloud computing: A [virtual private server](https://en.wikipedia.org/wiki/Virtual_private_server). These “instances” can run [most Linux, BSD, and Windows operating systems](https://aws.amazon.com/ec2/faqs/#What_operating_system_environments_are_supported). Internally, they've used a heavily modified [Xen](https://en.wikipedia.org/wiki/Xen) virtualization. That said, new instance classes are being introduced with a KVM derived hypervisor instead, called [Nitro](http://www.brendangregg.com/blog/2017-11-29/aws-ec2-virtualization-2017.html). So far, this is limited to the C5 and M5 instance types. Lastly, there's a \"bare metal hypervisor\" available for [i3.metal instances](https://aws.amazon.com/about-aws/whats-new/2018/05/announcing-general-availability-of-amazon-ec2-bare-metal-instances/)\n-\tThe term “EC2” is sometimes used to refer to the servers themselves, but technically refers more broadly to a whole collection of supporting services, too, like load balancing (CLBs/ALBs/NLBs), IP addresses (EIPs), bootable images (AMIs), security groups, and network drives (EBS) (which we discuss individually in this guide).\n-\t**💸[EC2 pricing](https://aws.amazon.com/ec2/pricing/)** and **[cost management](#ec2-cost-management)** is a complicated topic. It can range from free (on the [AWS free tier](https://aws.amazon.com/free/)) to a lot, depending on your usage. Pricing is by instance type, by second or hour, and changes depending on AWS region and whether you are purchasing your instances [On-Demand](https://aws.amazon.com/ec2/pricing/on-demand/), on the [Spot market](https://aws.amazon.com/ec2/spot/) or pre-purchasing ([Reserved Instances](https://aws.amazon.com/ec2/pricing/reserved-instances/)).\n- **Network Performance:** For some instance types, AWS uses general terms like Low, Medium, and High to refer to network performance. Users have done [benchmarking](http://stackoverflow.com/questions/18507405/ec2-instance-typess-exact-network-performance) to provide expectations for what these terms can mean.\n\n[Back to top :arrow_up:](#table-of-contents)\n### EC2 Alternatives and Lock-In\n\n-\tRunning EC2 is akin to running a set of physical servers, as long as you don’t do automatic scaling or tooled cluster setup. If you just run a set of static instances, migrating to another VPS or dedicated server provider should not be too hard.\n-\t🚪**Alternatives to EC2:** The direct alternatives are Google Cloud, Microsoft Azure, Rackspace, DigitalOcean, AWS's own Lightsail offering, and other VPS providers, some of which offer similar APIs for setting up and removing instances. (See the comparisons [above](#when-to-use-aws).)\n-\t**Should you use Amazon Linux?** AWS encourages use of their own [Amazon Linux](https://aws.amazon.com/amazon-linux-ami/), which is evolved from [Red Hat Enterprise Linux (RHEL)](https://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux) and [CentOS](https://en.wikipedia.org/wiki/CentOS). It’s used by many, but [others are skeptical](https://www.exratione.com/2014/08/do-not-use-amazon-linux/). Whatever you do, think this decision through carefully. It’s true Amazon Linux is heavily tested and better supported in the unlikely event you have deeper issues with OS and virtualization on EC2. But in general, many companies do just fine using a standard, non-Amazon Linux distribution, such as Ubuntu or CentOS. Using a standard Linux distribution means you have an exactly replicable environment should you use another hosting provider instead of (or in addition to) AWS. It’s also helpful if you wish to test deployments on local developer machines running the same standard Linux distribution (a practice that’s getting more common with Docker, too. Amazon now supports an official [Amazon Linux Docker image](http://docs.aws.amazon.com/AmazonECR/latest/userguide/amazon_linux_container_image.html), aimed at assisting with local development on a comparable environment, though this is new enough that it should be considered experimental). Note that the currently-in-testing [Amazon Linux 2](https://aws.amazon.com/about-aws/whats-new/2017/12/introducing-amazon-linux-2/) supports on-premise deployments explicitly.\n-\t**EC2 costs:** See the [section on this](#ec2-cost-management).\n\n[Back to top :arrow_up:](#table-of-contents)\n### EC2 Tips\n\n-\t🔹**Picking regions:** When you first set up, consider which [regions](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) you want to use first. Many people in North America just automatically set up in the us-east-1 (N. Virginia) region, which is the default, but it’s worth considering if this is best up front. You'll want to evaluate service availability (some services [are not available in all regions](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)), costing (baseline costs also [vary by region](https://aws.amazon.com/ec2/pricing/) by up to 10-30% (generally lowest in us-east-1 for comparison purposes)), and compliance (various countries have differing regulations with regard to data privacy, for example).\n-\t**Instance types:** EC2 instances come in many types, corresponding to the capabilities of the virtual machine in CPU architecture and speed, RAM, disk sizes and types (SSD or magnetic), and network bandwidth.\n\t-\tSelecting instance types is complex since there are so many types. Additionally there are different generations, released [over the years](https://aws.amazon.com/blogs/aws/ec2-instance-history/).\n\t-\t🔹Use the list at [**ec2instances.info**](http://www.ec2instances.info/) to review costs and features. [Amazon’s own list](https://aws.amazon.com/ec2/instance-types/) of instance types is hard to use, and doesn’t list features and price together, which makes it doubly difficult.\n\t-\tPrices vary a lot, so use [**ec2instances.info**](http://www.ec2instances.info/) to determine the set of machines that meet your needs and [**ec2price.com**](http://ec2price.com/) to find the cheapest type in the region you’re working in. Depending on the timing and region, it might be much cheaper to rent an instance with *more* memory or CPU than the bare minimum.\n  - **Turn off** your instances when they aren’t in use. For many situations such as testing or staging resources, you may not need your instances on 24/7, and you won’t need to pay EC2 running costs when they are suspended. Given that costs are calculated based on usage, this is a simple mechanism for cost savings. This can be achieved using [Lambda and CloudWatch](https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/), deploying the [Instance Scheduler](https://aws.amazon.com/solutions/implementations/instance-scheduler/) solution, an open source option like [cloudcycler](https://github.com/fairfaxmedia/cloudcycler), or a SaaS provider like [GorillaStack](https://www.gorillastack.com). (Note: if you turn off instances with an ephemeral root volume, any state will be lost when the instance is turned off. Therefore, for stateful applications it is safer to turn off EBS backed instances).\n-\t[**Dedicated instances**](https://aws.amazon.com/ec2/purchasing-options/dedicated-instances/) and [**dedicated hosts**](https://aws.amazon.com/ec2/dedicated-hosts/) are assigned hardware, instead of usual virtual instances. They are more expensive than virtual instances but [can be preferable](https://aws.amazon.com/ec2/dedicated-hosts/) for performance, compliance, financial modeling, or licensing reasons.\n-\t**32 bit vs 64 bit:** A few micro, small, and medium instances are still available to use as 32-bit architecture. You’ll be using 64-bit EC2 (“amd64”) instances nowadays, though smaller instances still support 32 bit (“i386”). Use 64 bit unless you have legacy constraints or other good reasons to use 32.\n-\t**HVM vs PV:** There are two kinds of virtualization technology used by EC2, [hardware virtual machine (HVM) and paravirtual (PV)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/virtualization_types.html). Historically, PV was the usual type, but [now HVM is becoming the standard](https://www.opswat.com/blog/aws-2015-why-you-need-switch-pv-hvm). If you want to use the newest instance types, you must use HVM. See the [instance type matrix](https://aws.amazon.com/amazon-linux-ami/instance-type-matrix/) for details.\n-\t**Operating system:** To use EC2, you’ll need to pick a base operating system. It can be Windows or Linux, such as Ubuntu or [Amazon Linux](https://aws.amazon.com/amazon-linux-ami/). You do this with AMIs, which are covered in more detail in their own section below.\n-\t**Limits:** You can’t create arbitrary numbers of instances. Default limits on numbers of EC2 instances per account vary by instance type, as described in [this list](http://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2).\n-\t❗**Use termination protection:** For any instances that are important and long-lived (in particular, aren't part of auto-scaling), [enable termination protection](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#Using_ChangingDisableAPITermination). This is an important line of defense against user mistakes, such as accidentally terminating many instances instead of just one due to human error.\n-\t**SSH key management:**\n\t-\tWhen you start an instance, you need to have at least one [ssh key pair](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) set up, to bootstrap, i.e., allow you to ssh in the first time.\n\t-\tAside from bootstrapping, you should manage keys yourself on the instances, assigning individual keys to individual users or services as appropriate.\n\t-\tAvoid reusing the original boot keys except by administrators when creating new instances.\n\t-\tAvoid sharing keys and [add individual ssh keys](http://security.stackexchange.com/questions/87480/managing-multiple-ssh-private-keys-for-a-team) for individual users.\n-\t**GPU support:** You can rent GPU-enabled instances on EC2 for use in machine learning or graphics rendering workloads.\n\n\t-\tThere are [three types](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using_cluster_computing.html) of GPU-enabled instances currently available:\n\t\t- The P3 series offers NVIDIA Tesla V100 GPUs in 1, 4 and 8 GPU configurations targeting machine learning, scientific workloads, and other high performance computing applications.\n\t\t- The P2 series offers NVIDIA Tesla K80 GPUs in 1, 8 and 16 GPU configurations targeting machine learning, scientific workloads, and other high performance computing applications.\n\t\t- The G3 series offers NVIDIA Tesla M60 GPUs in 1, 2, or 4 GPU configurations targeting graphics and video encoding.\n\t-\tAWS offers two different AMIs that are targeted to GPU applications. In particular, they target deep learning workloads, but also provide access to more stripped-down driver-only base images.\n\t\t-\tAWS offers both an Amazon Linux [Deep Learning AMI](https://aws.amazon.com/marketplace/pp/B077GF11NF?qid=1536363169916&sr=0-3&ref_=srh_res_product_title) (based on Amazon Linux) as well as an Ubuntu [Deep Learning AMI](https://aws.amazon.com/marketplace/pp/B077GCH38C). Both come with most NVIDIA drivers and ancillary software (CUDA, CUBLAS, CuDNN, TensorFlow, PyTorch, etc.) installed to lower the barrier to usage.\n\t\t-\t⛓ Note that using these AMIs can lead to lock in due to the fact that you have no direct access to software configuration or versioning.\n\t\t-\t🔸 The compendium of frameworks included can lead to long instance startup times and difficult-to-reason-about environments.\n\t-\t🔹As with any expensive EC2 instance types, [Spot instances can offer significant savings](#ec2-cost-management) with GPU workloads when interruptions are tolerable.\n- All current EC2 instance types can take advantage of IPv6 addressing, so long as they are launched in a subnet with an allocated CIDR range in an IPv6-enabled VPC.\n\n[Back to top :arrow_up:](#table-of-contents)\n### EC2 Gotchas and Limitations\n\n-\t❗Never use ssh passwords. Just don’t do it; they are too insecure, and consequences of compromise too severe. Use keys instead. [Read up on this](https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2) and fully disable ssh password access to your ssh server by making sure 'PasswordAuthentication no' is in your /etc/ssh/sshd_config file. If you’re careful about managing ssh private keys everywhere they are stored, it is a major improvement on security over password-based authentication.\n-\t🔸For all [newer instance types](https://aws.amazon.com/amazon-linux-ami/instance-type-matrix/), when selecting the AMI to use, be sure you select the HVM AMI, or it just won’t work.\n-\t❗When creating an instance and using a new ssh key pair, [make sure the ssh key permissions are correct](http://stackoverflow.com/questions/1454629/aws-ssh-access-permission-denied-publickey-issue).\n-\t🔸Sometimes certain EC2 instances can get scheduled for retirement by AWS due to “detected degradation of the underlying hardware,” in which case you are given a couple of weeks to migrate to a new instance\n \t-\tIf your instance root device is an EBS volume, you can typically stop and then start the instance which moves it to healthy host hardware, giving you control over timing of this event. Note however that you will lose any instance store volume data ([ephemeral drives](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html)) if your instance type has instance store volumes.\n \t-\tThe instance public IP (if it has one) will likely change unless you're using Elastic IPs. This could be a problem if other systems depend on the IP address.\n-\t🔸Periodically you may find that your server or load balancer is receiving traffic for (presumably) a previous EC2 server that was running at the same IP address that you are handed out now (this may not matter, or it can be fixed by migrating to another new instance).\n-\t❗If the EC2 API itself is a critical dependency of your infrastructure (e.g. for automated server replacement, custom scaling algorithms, etc.) and you are running at a large scale or making many EC2 API calls, make sure that you understand when they might fail (calls to it are [rate limited](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html#api-request-rate) and the limits are not published and subject to change) and code and test against that possibility.\n-\t❗Many newer EC2 instance types are either EBS-only, or backed by local NVMe disks assigned to the instance. Make sure to factor in EBS performance and costs when planning to use them.\n-\t❗If you're operating at significant scale, you may wish to break apart API calls that enumerate all of your resources, and instead operate either on individual resources, or a subset of the entire list. EC2 APIs will time out! Consider using [filters](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) to restrict what gets returned.\n-\t❗⏱ Instances come in two types: **Fixed Performance Instances** (e.g. M3, C3, and R3) and [**Burstable Performance Instances**](https://aws.amazon.com/ec2/instance-types/#burst) (e.g. T2). A T2 instance receives CPU credits continuously, the rate of which depends on the instance size. T2 instances accrue CPU credits when they are idle, and use CPU credits when they are active. However, once an instance runs out of credits, you'll notice a severe degradation in performance. If you need consistently high CPU performance for applications such as video encoding, high volume websites or HPC applications, it is recommended to use Fixed Performance Instances.\n-\tInstance user-data is [limited to 16 KB](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-add-user-data). (This limit applies to the data in raw form, not base64-encoded form.) If more data is needed, it can be downloaded from S3 by a user-data script.\n-\tVery new accounts may not be able to launch some instance types, such as GPU instances, because of an initially imposed “soft limit” of zero. This limit can be raised by making a support request. See [AWS Service Limits](http://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html) for the method to make the support request. Note that this limit of zero is [not currently documented](http://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_ec2).\n- Since multiple AWS instances all run on the same physical hardware, early cloud adopters encountered what became known as the [Noisy Neighbor problem](https://searchcloudcomputing.techtarget.com/definition/noisy-neighbor-cloud-computing-performance). This feeling of not getting what you are paying for led to [user frustration](https://twitter.com/technicallyjosh/status/668963405831651328), however \"steal\" may not be the best word to describe what's actually happening based on a [detailed explanation of how the kernel determine steal time](https://support.cloud.engineyard.com/hc/en-us/community/posts/203751578-Explanation-of-Steal-Time). Avoiding having CPU steal affect your application in the cloud may be best handled by [properly designing your cloud architecture](https://www.infoworld.com/article/3073503/cloud-computing/debunking-the-clouds-noisy-neighbor-myth.html).\n- AWS [introduced Dedicated Tenancy](https://aws.amazon.com/blogs/aws/amazon-ec2-dedicated-instances/) in 2011. This allows customers to have all resources from a single server. Some saw this as a way to solve the [noisy neighbor problem](https://www.infoworld.com/article/3008225/cloud-computing/amazon-dedicated-hosts-bye-bye-to-noisy-cloud-neighbors.html) since only that customer uses the CPU. This approach comes with a significant risk if that physical system needed any type of maintenance. If a customer had 20 instances running using shared tenancy and one underlying server needed maintenance, only the instance on that server would go offline. If that customer had 20 instances running using dedicated tenancy, when the underlying server needs maintenance, all 20 instances would go offline.\n-\t🔸Only **i3.metal** type instances providing an ability to run Android x86 emulators on AWS at the moment.\n\n\n\nCloudWatch\n-------------------\n\n### CloudWatch Basics\n\n* 📒  [Homepage](https://aws.amazon.com/cloudwatch/) ∙ [Documentation](https://aws.amazon.com/documentation/cloudwatch/) ∙ [FAQ](https://aws.amazon.com/cloudwatch/faqs/) ∙ [Pricing](https://aws.amazon.com/cloudwatch/pricing/)\n* **CloudWatch** monitors resources and applications, captures logs, and sends events.\n* CloudWatch monitoring is the standard mechanism for keeping tabs on AWS resources. A wide range of  [**metrics and dimensions**](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CW_Support_For_AWS.html) are available via CloudWatch, allowing you to create time based graphs, **[alarms](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)**, and **[dashboards](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)**.\n    * Alarms are the most practical use of CloudWatch, allowing you to trigger notifications from any given metric.\n    * Alarms can trigger [SNS notifications](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ConsoleAlarms.html), [Auto Scaling actions](http://docs.aws.amazon.com/autoscaling/latest/userguide/policy_creating.html), or [EC2 actions](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html).\n    * Alarms also support [alerting when any M out of N datapoints cross the alarm threshold](https://aws.amazon.com/about-aws/whats-new/2017/12/amazon-cloudwatch-alarms-now-alerts-you-when-any-m-out-of-n-metric-datapoints-in-an-interval-are-above-your-threshold/).\n    * Publish and share graphs of metrics by creating [customizable dashboard views](https://aws.amazon.com/blogs/aws/cloudwatch-dashboards-create-use-customized-metrics-views/).\n\t\t* Monitor and report on EC2 [instance system check failure alarms](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html#creating_status_check_alarms).\n* **Using CloudWatch Events:**\n    * Events create a mechanism to automate actions in various services on AWS. You can create [event rules](http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html) from instance states, AWS APIs, Auto Scaling, Run commands, deployments or time-based schedules (think Cron).\n    * [Triggered events](http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CWE_GettingStarted.html) can invoke Lambda functions, send SNS/SQS/Kinesis messages, or perform instance actions (terminate, restart, stop, or snapshot volumes).\n    * Custom payloads can be sent to targets in JSON format, this is especially useful when triggering Lambdas.\n* **Using CloudWatch Logs:**\n    * [CloudWatch Logs](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) is a streaming log storage system. By storing logs within AWS you have access to unlimited paid storage, but you also have the option of streaming logs directly to ElasticSearch or custom Lambdas.\n    * A [log agent installed](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_GettingStarted.html) on your servers will process logs over time and send them to CloudWatch Logs.\n    * You can [export logged data to S3](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/S3Export.html) or stream results to other AWS services.\n    * CloudWatch Logs can be [encrypted using keys managed through KMS](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html).\n* **Detailed monitoring:** [Detailed monitoring](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch-new.html) for EC2 instances must be enabled to get granular metrics, and is [billed under CloudWatch](https://aws.amazon.com/cloudwatch/pricing/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### CloudWatch Alternatives and Lock-In\n\n* CloudWatch offers fairly basic functionality that doesn't create significant (additional) AWS lock-in. Most of the metrics provided by the service can be obtained through APIs that can be imported into other aggregation or visualization tools or services (many specifically provide CloudWatch data import services).\n* 🚪 Alternatives to CloudWatch monitoring services include [NewRelic](http://newrelic.com/), [Datadog](http://datadog.com/), [Sumo Logic](http://sumologic.com/), [Zabbix](http://zabbix.com/), [Nagios](http://nagios.org/), [Ruxit](http://ruxit.com/), [Elastic Stack](https://www.elastic.co/elk-stack), open source options such as [StatsD](https://github.com/etsy/statsd) or [collectd](https://collectd.org/) with [Graphite](https://graphiteapp.org/), and many others.\n* 🚪 CloudWatch Log alternatives include [Splunk](http://splunk.com/), [Sumo Logic](http://sumologic.com/), [Loggly](http://loggly.com/), [LogDNA](https://logdna.com/), [Logstash](https://www.elastic.co/products/logstash), [Papertrail](https://papertrailapp.com/), [Elastic Stack](https://www.elastic.co/elk-stack), and other centralized logging solutions.\n\n[Back to top :arrow_up:](#table-of-contents)\n### CloudWatch Tips\n\n* Some very common use cases for CloudWatch are **[billing alarms](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html)**, **instance** **or [load balancer up/down alarms](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-cloudwatch-metrics.html)**, and **disk usage alerts**.\n* You can use [EC2Config](http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_WinAMI.html#send_logs_to_cwl) to monitor watch memory and disk metrics on Windows platform instances. For Linux, there are [example scripts](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/mon-scripts.html) that do the same thing.\n* You can [publish your own metrics](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html) using the AWS API. [Incurs additional cost](https://aws.amazon.com/cloudwatch/pricing/).\n* You can stream directly from CloudWatch Logs to a Lambda or ElasticSearch cluster by creating [subscriptions](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Subscriptions.html) on Log Groups.\n* Don't forget to take advantage of the [CloudWatch non-expiring free tier](https://aws.amazon.com/free/#Amazon_CloudWatch).\n\n[Back to top :arrow_up:](#table-of-contents)\n### CloudWatch Gotchas and Limitations\n\n* 🔸Metrics in CloudWatch originate [on the hypervisor](https://forums.aws.amazon.com/message.jspa?messageID=403578). The hypervisor doesn't have access to OS information, so certain metrics (most notably memory utilization) are not available unless pushed to CloudWatch from inside the instance.\n* 🔸You can not use [more than one metric for an alarm](https://forums.aws.amazon.com/thread.jspa?threadID=94984).\n* 🔸Notifications you receive from alarms will not have any contextual detail; they have only the specifics of the threshold, alarm state, and timing.\n* 🔸By default, CloudWatch metric resolution is 1 minute. If you send multiple values of a metric within the same minute, they will be aggregated into minimum, maximum, average and total (sum) per minute.\n* 🐥In July 2017, a new [high-resolution option](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html#high-resolution-metrics) was added for CloudWatch metrics and alarms. This feature allows you to record metrics with 1-second resolution, and to evaluate CloudWatch alarms every 10 seconds.\n    - The [blog post introducing this feature](https://aws.amazon.com/blogs/aws/new-high-resolution-custom-metrics-and-alarms-for-amazon-cloudwatch/) describes how to publish a high-resolution metric to CloudWatch. Note that when calling the `PutMetricData` API, `StorageResolution` is an attribute of each item you send in the `MetricData` array, not a direct parameter of the `PutMetricData` API call.\n* 🔸Data about metrics is kept in CloudWatch [for 15 months](https://aws.amazon.com/blogs/aws/amazon-cloudwatch-update-extended-metrics-retention-user-interface-update/), starting November 2016 (used to be 14 days). Minimum granularity increases after 15 days.\n\nAMIs\n----\n\n### AMI Basics\n\n-\t📒 [User guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)\n-\t**AMIs** (Amazon Machine Images) are immutable images that are used to launch preconfigured EC2 instances. They come in both public and private flavors. Access to public AMIs is either freely available (shared/community AMIs) or bought and sold in the [**AWS Marketplace**](http://aws.amazon.com/marketplace).\n-\tMany operating system vendors publish ready-to-use base AMIs. For Ubuntu, see the [Ubuntu AMI Finder](https://cloud-images.ubuntu.com/locator/ec2/). Amazon of course has [AMIs for Amazon Linux](https://aws.amazon.com/amazon-linux-ami/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### AMI Tips\n\n-\tAMIs are built independently based on how they will be deployed. You must select AMIs that match your deployment when using them or creating them:\n\t-\tEBS or instance store\n\t-\tPV or HVM [virtualization types](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/virtualization_types.html)\n\t-\t32 bit (“i386”) vs 64 bit (“amd64”) architecture\n-\tAs discussed above, modern deployments will usually be with **64-bit EBS-backed HVM**.\n-\tYou can create your own custom AMI by [snapshotting the state](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html) of an EC2 instance that you have modified.\n-\t[AMIs backed by EBS storage](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device) have the necessary image data loaded into the EBS volume itself and don’t require an extra pull from S3, which results in EBS-backed instances coming up much faster than instance storage-backed ones.\n-\t**AMIs are per region**, so you must look up AMIs in your region, or copy your AMIs between regions with the [AMI Copy](https://aws.amazon.com/about-aws/whats-new/2013/03/12/announcing-ami-copy-for-amazon-ec2/) feature.\n-\tAs with other AWS resources, it’s wise to [use tags](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) to version AMIs and manage their lifecycle.\n-\tIf you create your own AMIs, there is always some tension in choosing how much installation and configuration you want to “bake” into them.\n\t-\tBaking less into your AMIs (for example, just a configuration management client that downloads, installs, and configures software on new EC2 instances when they are launched) allows you to minimize time spent automating AMI creation and managing the AMI lifecycle (you will likely be able to use fewer AMIs and will probably not need to update them as frequently), but results in longer waits before new instances are ready for use and results in a higher chance of launch-time installation or configuration failures.\n\t-\tBaking more into your AMIs (for example, pre-installing but not fully configuring common software along with a configuration management client that loads configuration settings at launch time) results in a faster launch time and fewer opportunities for your software installation and configuration to break at instance launch time but increases the need for you to create and manage a robust AMI creation pipeline.\n\t-\tBaking even more into your AMIs (for example, installing all required software as well and potentially also environment-specific configuration information) results in fast launch times and a much lower chance of instance launch-time failures but (without additional re-deployment and re-configuration considerations) can require time consuming AMI updates in order to update software or configuration as well as more complex AMI creation automation processes.\n-\tWhich option you favor depends on how quickly you need to scale up capacity, and size and maturity of your team and product.\n\t-\tWhen instances boot fast, auto-scaled services require less spare capacity built in and can more quickly scale up in response to sudden increases in load. When setting up a service with autoscaling, consider baking more into your AMIs and backing them with the EBS storage option.\n\t-\tAs systems become larger, it common to have more complex AMI management, such as a multi-stage AMI creation process in which few (ideally one) common base AMIs are infrequently regenerated when components that are common to all deployed services are updated and then a more frequently run “service-level” AMI generation process that includes installation and possibly configuration of application-specific software.\n-\tMore thinking on AMI creation strategies [here](http://techblog.netflix.com/2013/03/ami-creation-with-aminator.html).\n-\tUse tools like [Packer](https://packer.io/) to simplify and automate AMI creation.\n-\tIf you use RHEL instances and happen to have existing RHEL on-premise Red Hat subscriptions, then you could leverage Red Hat's [Cloud Access program](https://www.redhat.com/en/technologies/cloud-computing/cloud-access) to migrate a portion of your subscriptions to AWS, and thereby not having AWS charge you for RHEL subscriptions a second time. You can either use your own self-created RHEL AMI's or Red Hat provided [Gold Images](https://access.redhat.com/articles/2962171) that will be added to your private AMI's once you sign up for Red Hat Cloud Access.\n\n[Back to top :arrow_up:](#table-of-contents)\n### AMI Gotchas and Limitations\n\n-\t🔸**Amazon Linux package versions:** [By default](https://aws.amazon.com/amazon-linux-ami/faqs/#lock), instances based on Amazon Linux AMIs are configured point to the latest versions of packages in Amazon’s package repository. This means that the package versions that get installed are not locked and it is possible for changes, including breaking ones, to appear when applying updates in the future. If you bake your AMIs with updates already applied, this is unlikely to cause problems in running services whose instances are based on those AMIs – breaks will appear at the earlier AMI-baking stage of your build process, and will need to be fixed or worked around before new AMIs can be generated. There is a “lock on launch” feature that allows you to configure Amazon Linux instances to target the repository of a particular major version of the Amazon Linux AMI, reducing the likelihood that breaks caused by Amazon-initiated package version changes will occur at package install time but at the cost of not having updated packages get automatically installed by future update runs. Pairing use of the “lock on launch” feature with a process to advance the Amazon Linux AMI at your discretion can give you tighter control over update behaviors and timings.\n-   **Cloud-Init Defaults:** Oftentimes users create AMIs after performing customizations (albeit manually or via some tool such as Packer or Ansible).  If you're not careful to alter cloud-init settings that correspond to the system service (e.g. sshd, etc.) you've customized, you may find that your changes are no longer in effect after booting your new AMI for the first time, as cloud-init has overwritten them.\n\n    Some distros have different files than others, but all are generally located in `/etc/cloud/`, regardless of distro.  You will want to review these files carefully for your chosen distro before rolling your own AMIs.  A [complete reference to cloud-init](https://cloudinit.readthedocs.io/en/latest/) is available on the cloud-init site.  This is an advanced configuration mechanism, so test any changes made to these files in a sandbox prior to any serious usage.\n\nAuto Scaling\n------------\n\n### Auto Scaling Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/autoscaling/) ∙ [User guide](http://docs.aws.amazon.com/autoscaling/latest/userguide/) ∙ [FAQ](https://aws.amazon.com/ec2/autoscaling/faqs/) ∙ [Pricing](https://aws.amazon.com/autoscaling/pricing/) at no additional charge\n-\t[**Auto Scaling Groups (ASGs)**](https://aws.amazon.com/autoscaling/) are used to control the number of instances in a service, reducing manual effort to provision or deprovision EC2 instances.\n-\tThey can be configured through [Scaling Policies](http://docs.aws.amazon.com/autoscaling/latest/userguide/policy_creating.html) to automatically increase or decrease instance counts based on metrics like CPU utilization, or based on a schedule.\n-\tThere are three common ways of using ASGs - dynamic (automatically adjust instance count based on metrics for things like CPU utilization), static (maintain a specific instance count at all times), scheduled (maintain different instance counts at different times of day or on days of the week).\n-\t💸ASGs [have no additional charge](https://aws.amazon.com/autoscaling/pricing/) themselves; you pay for underlying EC2 and CloudWatch services.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Auto Scaling Tips\n\n-\t💸 Better matching your cluster size to your current resource requirements through use of ASGs can result in significant cost savings for many types of workloads.\n-\tPairing ASGs with CLBs is a common pattern used to deal with changes in the amount of traffic a service receives.\n-\tDynamic Auto Scaling is easiest to use with stateless, horizontally scalable services.\n-\tEven if you are not using ASGs to dynamically increase or decrease instance counts, you should seriously consider maintaining all instances inside of ASGs – given a target instance count, the ASG will work to ensure that number of instances running is equal to that target, replacing instances for you if they die or are marked as being unhealthy. This results in consistent capacity and better stability for your service.\n-\tAutoscalers can be [configured to terminate](http://docs.aws.amazon.com/autoscaling/latest/userguide/healthcheck.html) instances that a CLB or ALB has marked as being unhealthy.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Auto Scaling Gotchas and Limitations\n\n-\t🔸**ReplaceUnhealthy setting:** By default, ASGs will kill instances that the EC2 instance manager considers to be unresponsive. It is possible for instances whose CPU is completely saturated for minutes at a time to appear to be unresponsive, causing an ASG with the default [ReplaceUnhealthy setting](http://docs.aws.amazon.com/autoscaling/latest/userguide/as-suspend-resume-processes.html#process-types) turned on to replace them. When instances that are managed by ASGs are expected to consistently run with very high CPU, consider deactivating this setting. If you do so, however, detecting and killing unhealthy nodes will become your responsibility.\n\nEBS\n---\n\n### EBS Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/ebs/) ∙ [User guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) ∙ [FAQ](https://aws.amazon.com/ebs/faqs/) ∙ [Pricing](https://aws.amazon.com/ebs/pricing/)\n-\t**EBS** (Elastic Block Store) provides block level storage. That is, it offers storage volumes that can be attached as filesystems, like traditional network drives.\n-\tEBS volumes can only be attached to one EC2 instance at a time. In contrast, EFS can be shared but has a much higher price point ([a comparison](http://stackoverflow.com/questions/29575877/aws-efs-vs-ebs-vs-s3-differences-when-to-use)).\n\n[Back to top :arrow_up:](#table-of-contents)\n### EBS Tips\n\n-\t⏱**RAID:** Use [RAID drives](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/raid-config.html) for [increased performance](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSPerformance.html).\n-\t⏱A worthy read is AWS’ [post on EBS IO characteristics](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-io-characteristics.html) as well as their [performance tips](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSPerformance.html#d0e86148).\n-\t⏱One can [provision IOPS](http://aws.amazon.com/ebs/details/) (that is, pay for a specific level of I/O operations per second) to ensure a particular level of performance for a disk.\n-\t⏱A single gp2 EBS volume allows 16k IOPS max To get the maximum performance out of a gp2 EBS volume, it has to be of a maximum size and attached to an EBS-optimized EC2 instance.\n- \t💸Standard and gp2 EBS volumes improve IOPS with size. It may make sense for you to simply enlarge a volume instead of paying for better performance explicitly. This can in many cases reduce costs by 2/3.\n-\tA standard block size for an EBS volume is 16kb.\n\n[Back to top :arrow_up:](#table-of-contents)\n### EBS Gotchas and Limitations\n\n-\t❗EBS durability is reasonably good for a regular hardware drive (annual failure rate of [between 0.1% - 0.2%](http://aws.amazon.com/ebs/details/#availabilityanddurability)). On the other hand, that is very poor if you don’t have backups! By contrast, S3 durability is extremely high. *If you care about your data, back it up to S3 with snapshots.*\n-\t🔸EBS has an [**SLA**](http://aws.amazon.com/ec2/sla/) with **99.99%** uptime. See notes on high availability below.\n-\t❗EBS volumes have a [**volume type**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) indicating the physical storage type. The types called “standard” (**st1** or **sc1**) are actually old spinning-platter disks, which deliver only hundreds of IOPS — not what you want unless you’re really trying to cut costs. Modern SSD-based **gp2** or **io1** are typically the options you want.\n-\t❗When restoring a snapshot to create an EBS volume, blocks are lazily read from S3 the first time they're referenced. To avoid an initial period of high latency, you may wish to use `dd` or `fio` as per the [official documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-restoring-volume.html).\n\nEFS\n---\n\n\n### EFS Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/efs/) ∙ [User guide](http://docs.aws.amazon.com/efs/latest/ug) ∙ [FAQ](https://aws.amazon.com/efs/faq/) ∙ [Pricing](https://aws.amazon.com/efs/pricing/)\n-\t🐥**EFS** is Amazon’s network filesystem. It’s presented as an [NFSv4.1](https://en.wikipedia.org/wiki/Network_File_System#NFSv4) server. Any compatible NFSv4 client can mount it.\n-\tIt is designed to be highly available and durable and each EFS file system object is redundantly stored across multiple availability zones.\n-\tEFS is designed to be used as a shared network drive and it can automatically scale up to petabytes of stored data and thousands of instances attached to it.\n-\tEFS can offer [higher throughput](http://docs.aws.amazon.com/efs/latest/ug/performance.html) (multiple gigabytes per second) and better durability and availability than EBS (see [the comparison table](#storage-durability-availability-and-price)), but with higher latency.\n-\tEFS is priced based on the volume of data stored, and costs [much more than EBS](#storage-durability-availability-and-price); it's in the ballpark of three times as much compared to general purpose gp2 EBS volumes.\n-\t⏱ [Performance](http://docs.aws.amazon.com/efs/latest/ug/performance.html) is dependent on the volume of data stored, as is the price:\n\t-\tLike EBS, EFS uses a credit based system. Credits are earned at a rate of 50 KiB/s per GiB of storage and consumed in bursts during reading/writing files or metadata. Unlike EBS, operations on metadata (file size, owner, date, etc.) also consume credits. The [BurstCreditBalance metric](http://docs.aws.amazon.com/efs/latest/ug/monitoring-cloudwatch.html#efs-metrics) in CloudWatch should be monitored to make sure the file system doesn't run out of credits.\n\t-\tThroughput capacity during bursts is also dependent on size. Under 1 TiB, throughput can go up to 100 MiB/s. Above that, 100 MiB/s is added for each stored TiB. For instance, a file system storing 5 TiB would be able to burst at a rate of 500 MiB/s. Maximum throughput per EC2 instance is 250 MiB/s.\n\t-\tEFS has two performance modes that can only be set when a file system is created. One is \"General Purpose\", the other is \"Max I/O\". Max I/O scales higher, but at the cost of higher latency. When in doubt, use General Purpose, which is also the default. If the [PercentIOLimit metric](http://docs.aws.amazon.com/efs/latest/ug/monitoring-cloudwatch.html#efs-metrics) in CloudWatch hovers around 100%, Max I/O is recommended. Changing performance mode means creating a new EFS and migrating data.\n-\tHigh availability is achieved by having [mount targets in different subnets / availability zones](http://docs.aws.amazon.com/efs/latest/ug/images/overview-flow.png).\n\n[Back to top :arrow_up:](#table-of-contents)\n### EFS Tips\n\n-\tWith EFS being based on NFSv4.1, any directory on the EFS can be mounted directly, it doesn't have to be the root directory. One application could mount *fs-12345678:/prog1*, another *fs-12345678:/prog2*.\n-\t[User and group level permissions](https://docs.aws.amazon.com/efs/latest/ug/accessing-fs-nfs-permissions.html) can be used to control access to certain directories on the EFS file system.\n-\t⏱ **Sharing EFS filesystems:** One EFS filesystem can be used for multiple applications or services, but it should be considered carefully:\n\n\tPros:\n\t- Because performance is based on total size of stored files, having everything on one drive will increase performance for everyone. One application consuming credits faster than it can accumulate might be offset by another application that just stores files on EFS and rarely accesses them.\n\n\tCons:\n\t- Since credits are shared, if one application over-consumes them, it will affect the others.\n\t- A compromise is made with regards to [security](http://docs.aws.amazon.com/efs/latest/ug/security-considerations.html): all clients will have to have network access to the drive. Someone with root access on one client instance can mount any directory on the EFS and they have read-write access to all files on the drive, even if they don't have access to the applications hosted on other clients. There isn't a no-root-squash equivalent for EFS.\n\n[Back to top :arrow_up:](#table-of-contents)\n### EFS Gotchas and Limitations\n\n-\t🔸 A number of NFSv4.1 features are [not supported](http://docs.aws.amazon.com/efs/latest/ug/nfs4-unsupported-features.html) and there are some [limits](http://docs.aws.amazon.com/efs/latest/ug/limits.html) to the service.\n-\t🔸 As of 2017-08, EFS offers disk level encryption for new drives. For file systems created before that date, encryption can only be achieved by moving the data to a new EFS volume.\n-\t🔸 An EFS file system [can be mounted on premises](https://aws.amazon.com/efs/faq/#on-premises) over Direct Connect.\n-\t🔸 An EFS file system can NOT be mounted over VPC peering or VPN, even if the VPN is running on top of Direct Connect.\n-\t🔸 Using an EFS volume on Windows is not supported.\n-\t⏱ When a file is uploaded to EFS, it can take hours for EFS to update the details for billing and burst credit purposes.\n-\t🔸⏱  Metadata operations can be costly in terms of burst credit consumption. Recursively traversing a tree containing thousands of files can easily ramp up to tens or even hundreds of megabytes of burst credits being consumed, even if no file is being touched. Commands like ```find``` or ```chown -R``` can have an adverse impact on performance.\n\n\nLoad Balancers\n--------------\n\n### Load Balancer Basics\n\n-\tAWS has 3 load balancing products - “Classic Load Balancers” (CLBs), “Application Load Balancers” (ALBs), and \"Network Load Balancers\" (NLB).\n-\tBefore the introduction of ALBs, “Classic Load Balancers” were known as “Elastic Load Balancers” (ELBs), so older documentation, tooling, and blog posts may still reference “ELBs”.\n-\tCLBs have been around since 2009, ALBs in 2016, NLBs were added in 2017 to AWS.\n-\tCLBs support TCP and HTTP load balancing. ALBs support HTTP load balancing only. NLBs support TCP layer 4 load balancing.\n-\tCLBs and ALBs can optionally handle termination for a single SSL certificate.\n-\tAll can optionally perform active health checks of instances and remove them from the destination pool if they become unhealthy.\n-\tCLBs don't support complex / rule-based routing. ALBs support a (currently small) set of rule-based routing features. NLBs have most extensive routing options.\n-\tCLBs can only forward traffic to a single globally configured port on destination instances, while ALBs can forward to ports that are configured on a per-instance basis, better supporting routing to services on shared clusters with dynamic port assignment (like ECS or Mesos). NLBs support multiple ports on same IP; registering targets by IP address, including targets outside the VPC for the load balancer; ECS can select unused port for scheduling a task then register a target group using this port.\n-\tCLBs are supported in EC2 Classic as well as in VPCs while ALBs are supported in VPCs only.\n-   ALBs can target groups of instances and IP based targets in the RFC1918 ranges allowing you to use on premise destinations via VPN or Direct Connect.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Load Balancer Tips\n\n-\tIf you don’t have opinions on your load balancing up front, and don’t have complex load balancing needs like application-specific routing of requests, it’s reasonable just to use a CLB or ALB for load balancing instead.\n-\tEven if you don’t want to think about load balancing at all, because your architecture is so simple (say, just one server), put a load balancer in front of it anyway. This gives you more flexibility when upgrading, since you won’t have to change any DNS settings that will be slow to propagate, and also it lets you do a few things like terminate SSL more easily.\n-\t**CLBs and ALBs have many IPs:** Internally, an AWS load balancer is simply a collection of individual software load balancers hosted within EC2, with DNS load balancing traffic among them. The pool can contain many IPs, at least one per availability zone, and depending on traffic levels. They also support SSL termination, which is very convenient.\n-\t**Scaling:** CLBs and ALBs can scale to very high throughput, but scaling up is not instantaneous. If you’re expecting to be hit with a lot of traffic suddenly, it can make sense to load test them so they scale up in advance. You can also [contact Amazon](http://aws.amazon.com/articles/1636185810492479) and have them “pre-warm” the load balancer.\n-\t**Client IPs:** In general, if servers want to know true client IP addresses, load balancers must forward this information somehow. CLBs add the standard [X-Forwarded-For](https://en.wikipedia.org/wiki/X-Forwarded-For) header. When using a CLB as an HTTP load balancer, it’s possible to get the client’s IP address from this.\n-\t**Using load balancers when deploying:** One common pattern is to swap instances in the load balancer after spinning up a new stack with your latest version, keep old stack running for one or two hours, and either flip back to old stack in case of problems or tear it down.\n-   **Rotating Certificates while retaining ARN:** Rotating IAM Server Certificates can be difficult as the standard practice is to upload a new one then update all resources with the new ARN. You can however retain the same ARN using the `update-certificate` call with the following process:\n  1. Upload a new IAM Server Certificate with a unique name (e.g fuzzy.com.new)\n  2. Rename the existing IAM Server Certificate (e.g fuzzy.com to fuzzy.com.expired)\n  3. Rename the new IAM Server Certificate to the name of the previously existing certificate (e.g fuzzy.com.new to fuzzy.com)\n  4. Jiggle the CLB/ALB Listener to pick up the change:\n      * ALB: Invoke modify-listener with the existing details for the ALB Listener\n\t  * CLB: Invoke create-load-balancer-listeners with the existing details for the CLB listener\n\n[Back to top :arrow_up:](#table-of-contents)\n### Load Balancer Gotchas and Limitations\n\n-\t❗CLBs and ALBs have **no fixed external IP** that all clients see. For most consumer apps this doesn’t matter, but enterprise customers of yours may want this. IPs will be different for each user, and will vary unpredictably for a single client over time (within the standard [EC2 IP ranges](http://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html)). And similarly, never resolve a CLB name to an IP and put it as the value of an A record — it will work for a while, then break!\n-\t❗Some web clients or reverse proxies cache DNS lookups for a long time, which is problematic for CLBs and ALBs, since they change their IPs. This means after a few minutes, hours, or days, your client will stop working, unless you disable DNS caching. Watch out for [Java’s settings](http://docs.oracle.com/javase/8/docs/api/java/net/InetAddress.html) and be sure to [adjust them properly](http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/java-dg-jvm-ttl.html). Another example is nginx as a reverse proxy, which [normally resolves backends only at start-up](https://www.jethrocarr.com/2013/11/02/nginx-reverse-proxies-and-dns-resolution/) (although there is [a way to get around this](https://tenzer.dk/nginx-with-dynamic-upstreams/)).\n-\t❗It’s not unheard of for IPs to be recycled between customers without a long cool-off period. So as a client, if you cache an IP and are not using SSL (to verify the server), you might get not just errors, but responses from completely different services or companies!\n-\t🔸As an operator of a service behind a CLB or ALB, the latter phenomenon means you can also see puzzling or erroneous requests by clients of other companies. This is most common with clients using back-end APIs (since web browsers typically cache for a limited period).\n-\t❗CLBs and ALBs take time to scale up, it does not handle sudden spikes in traffic well. Therefore, if you anticipate a spike, you need to “pre-warm” the load balancer by gradually sending an increasing amount of traffic.\n-\t❗Tune your healthchecks carefully — if you are too aggressive about deciding when to remove an instance and conservative about adding it back into the pool, the service that your load balancer is fronting may become inaccessible for seconds or minutes at a time. Be extra careful about this when an autoscaler is configured to terminate instances that are marked as being unhealthy by a managed load balancer.\n-\t❗CLB HTTPS listeners don't support Server Name Indication (SNI). If you need SNI, you can work around this limitation by either providing a certificate with Subject Alternative Names (SANs) or by using TCP listeners and terminating SSL at your backend.\n-\t🔸 There is a limit on the number of ALBs, CLBs and NLBs per region (separately). As of late 2017, the default limit for each is 20 per region. These limits can be easily raised for ALB and CLB, but AWS is quite reluctant to raise the limit on NLBs.\n-\t🔸 If using a Network Load Balancer (NLB) then EC2 clients cannot connect to an NLB that resides in another VPC (VPC Peering) or AWS managed VPN unless the EC2 client is a C5, i3.metal or M5 instance type. For VPC peering, both VPCs must be in the same region. See [Troubleshooting](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-troubleshooting.html#target-not-in-service).\n\nCLB\n---\n\n### CLB Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/elasticloadbalancing/classicloadbalancer/) ∙ [User guide](https://aws.amazon.com/elasticloadbalancing/classicloadbalancer/developer-resources/) ∙ [FAQ](https://aws.amazon.com/elasticloadbalancing/classicloadbalancer/faqs/) ∙ [Pricing](https://aws.amazon.com/elasticloadbalancing/classicloadbalancer/pricing/)\n- Classic Load Balancers, formerly known as Elastic Load Balancers, are HTTP and TCP load balancers that are managed and scaled for you by Amazon.\n\n[Back to top :arrow_up:](#table-of-contents)\n### CLB Tips\n\n-\t**Best practices:** [This article](http://aws.amazon.com/articles/1636185810492479) is a must-read if you use CLBs heavily, and has a lot more detail.\n\n[Back to top :arrow_up:](#table-of-contents)\n### CLB Gotchas and Limitations\n\n-\tIn general, CLBs are not as “smart” as some load balancers, and don’t have fancy features or fine-grained control a traditional hardware load balancer would offer. For most common cases involving sessionless apps or cookie-based sessions over HTTP, or SSL termination, they work well.\n-\t🔸By default, CLBs will refuse to route traffic from a load balancer in one Availability Zone (AZ) to a backend instance in another. This [will cause 503s](http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/ts-elb-error-message.html#ts-elb-errorcodes-http503) if the last instance in an AZ becomes unavailable, even if there are healthy instances in other zones. If you’re running fewer than two backend instances per AZ, you almost certainly want to [enable cross-zone load balancing](http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-disable-crosszone-lb.html#enable-cross-zone).\n-\t🔸Complex rules for directing traffic are not supported. For example, you can’t direct traffic based on a regular expression in the URL, like HAProxy offers.\n-\t**Apex DNS names:** Once upon a time, you couldn’t assign a CLB to an apex DNS record (i.e. example.com instead of foo.example.com) because it needed to be an A record instead of a CNAME. This is now possible with a Route 53 alias record directly pointing to the load balancer.\n-\t🔸CLBs use [HTTP keep-alives](https://en.wikipedia.org/wiki/HTTP_persistent_connection) on the internal side. This can cause an unexpected side effect: Requests from different clients, each in their own TCP connection on the external side, can end up on the same TCP connection on the internal side. Never assume that multiple requests on the same TCP connection are from the same client!\n-\t🔸 Traffic between CLBs and back-end instances in the same subnet **will** have [Network ACL](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html) rules evaluated (EC2 to EC2 traffic in the same subnet would not have Network ACL rules evaluated). If the default '0.0.0.0/0 ALLOW' rule is removed from the Network ACL applied to the subnet, a rule that allows traffic on both the health check port and any listener port must be added.\n- As of December 2016, CLBs launched in VPCs do not support IPv6 addressing. CLBs launched in EC2-Classic support both IPv4 and IPv6 [with the \"dualstack\" DNS name](http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-internet-facing-load-balancers.html#internet-facing-ip-addresses).\n\nALB\n---\n\n### ALB Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/elasticloadbalancing/applicationloadbalancer/) ∙ [User guide](https://aws.amazon.com/elasticloadbalancing/applicationloadbalancer/developer-resources/) ∙ [FAQ](https://aws.amazon.com/elasticloadbalancing/applicationloadbalancer/faqs/) ∙ [Pricing](https://aws.amazon.com/elasticloadbalancing/applicationloadbalancer/pricing/)\n-\t🐥**Websockets and HTTP/2** are [now supported](https://aws.amazon.com/blogs/aws/new-aws-application-load-balancer/).\n-\t🐥**Internet Protocol Version 6 (IPv6)** is [now supported](https://aws.amazon.com/about-aws/whats-new/2017/01/announcing-internet-protocol-version-6-ipv6-support-for-elastic-load-balancing-in-amazon-virtual-private-cloud-vpc/).\n-\t🐥**Load Balancing via IP** is [now supported](https://aws.amazon.com/about-aws/whats-new/2017/08/elastic-load-balancing-application-load-balancer-now-supports-load-balancing-to-ip-addresses-as-targets-for-aws-and-on-premises-resources/).\n-\tPrior to the Application Load Balancer, you were advised to use TCP instead of HTTP as the protocol to make it work (as described [here](http://www.quora.com/When-will-Amazon-ELB-offer-SPDY-support)) and use [the obscure but useful Proxy Protocol](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/enable-proxy-protocol.html) ([more on this](https://chrislea.com/2014/03/20/using-proxy-protocol-nginx/)) to pass client IPs over a TCP load balancer.\n\n[Back to top :arrow_up:](#table-of-contents)\n### ALB Tips\n\n-\tUse ALBs to route to services that are hosted on shared clusters with dynamic port assignment (like ECS or Mesos).\n-\tALBs support [HTTP host-based routing](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#host-conditions) (send HTTP requests for “api.mydomain.com” -> {target-group-1}, “blog.mydomain.com” -> {target group 2}) as well as [HTTP path-based routing](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#path-conditions) (send HTTP requests for “/api/&ast;” ->  {target-group-1}, “/blog/&ast;” -> {target group 2}).\n\n[Back to top :arrow_up:](#table-of-contents)\n### ALB Gotchas and Limitations\n\n-\t🔸ALBs only support HTTP/2 over HTTPS (no plain-text HTTP/2).\n-\t🔸ALBs only support HTTP/2 to external clients and not to internal resources (instances/containers).\n-\tALBs support HTTP routing but not port-based TCP routing.\n-\tInstances in the ALB’s target groups have to either have a single, fixed healthcheck port (“EC2 instance”-level healthcheck) or the healthcheck port for a target has to be the same as its application port (“Application instance”-level healthcheck) - you can't configure a per-target healthcheck port that is different than the application port.\n-\tALBs are VPC-only (they are not available in EC2 Classic)\n-\tIn a target group, if there is no healthy target, all requests are routed to all targets. For example, if you point a listener at a target group containing a single service that has a long initialization phase (during which the health checks would fail), requests will reach the service while it is still starting up.\n- 📜 Although ALBs [now support SNI](https://aws.amazon.com/about-aws/whats-new/2017/10/elastic-load-balancing-application-load-balancers-now-support-multiple-ssl-certificates-and-smart-certificate-selection-using-server-name-indication-sni/), they only support 25 HTTPS certificates per Load Balancer. This limitation is not described [here](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-limits.html), so it might be subject to change.\n\nElastic Beanstalk\n----------------\n\n### Elastic Beanstalk Basics\n- 📒 [Homepage](https://aws.amazon.com/elasticbeanstalk/) ∙ [Developer guide](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/Welcome.html) ∙ [FAQ](https://aws.amazon.com/elasticbeanstalk/faqs/) ∙ [Pricing](https://aws.amazon.com/elasticbeanstalk/pricing/)\n- **EB** (Elastic Beanstalk) is a PaaS (Platform as a Service) that helps developers create, deploy and scale web applications\n- EB handles deployment, configuration, provisioning, load balancing, auto-scaling, monitoring, and logging\n- EB creates AWS resources on your behalf but you retain full access and control of the underlying resources\n- 💸 There is no cost to use EB but you will still be charged the full cost of the underlying AWS resources created by EB\n\n[Back to top :arrow_up:](#table-of-contents)\n### Elastic Beanstalk Tips\n- To speed up deployment before launch or in a dev stage, turn off health checks and set the `Deployment policy` to `All at once`\n- If you have a configuration you want to re-use for multiple EB apps, you can save the current configuration using `eb config save --cfg myEBConfig`\n- By default, EB doesn't have any alarms. You'll need to add them yourself on metrics that you're monitoring.\n- By default, EB doesn't enable [managed platform updates](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-platform-update-managed.html?icmpid=docs_elasticbeanstalk_console). Enable them in configuration to have EB automatically apply updates during a pre-specified maintenance window\n\n[Back to top :arrow_up:](#table-of-contents)\n### Elastic Beanstalk Gotchas and Limitations\n- 🔸 Don't edit [apache|nginx] conf files manually on ec2 instances as they will be re-written on each deployment (use [ebextensions](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions.html) instead)\n- 🔸 After creating an EB environment, it's no longer possible to change the `Name` tag\n- 🔸 EB will sometimes quarantine instances that cause multiple deployment issues. Despite being quarantined, EB will still deploy to them on subsequent deployments. To prevent this behavior, said instances will need to be terminated (or the underlying issue fixed)\n- File uploads are capped at 10MB for most default eb configurations - update [nginx config](https://stackoverflow.com/questions/18908426/increasing-client-max-body-size-in-nginx-conf-on-aws-elastic-beanstalk) to change\n- If you edit `.elasticbeanstalk/saved_configs/`, be aware that this is not kept in sync with the EB environment config. You'll need to manually fetch and save for changes to take effect\n\nElastic IPs\n-----------\n\n### Elastic IP Basics\n\n-\t📒 [Documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) ∙ [FAQ](https://aws.amazon.com/ec2/faqs/#Elastic_IP) ∙ [Pricing](https://aws.amazon.com/ec2/pricing/on-demand/#Elastic_IP_Addresses)\n-\t**Elastic IPs** are static IP addresses you can rent from AWS to assign to EC2 instances.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Elastic IP Tips\n\n-\t🔹**Prefer load balancers to elastic IPs:** For single-instance deployments, you could just assign elastic IP to an instance, give that IP a DNS name, and consider that your deployment. Most of the time, you should provision a [load balancer](#load-balancers) instead:\n\t-\tIt’s easy to add and remove instances from load balancers. It’s also quicker to add or remove instances from a load balancer than to reassign an elastic IP.\n\t-\tIt’s more convenient to point DNS records to load balancers, instead of pointing them to specific IPs you manage manually. They can also be Route 53 aliases, which are easier to change and manage.\n\t-\tBut in some situations, you do need to manage and fix IP addresses of EC2 instances, for example if a customer needs a fixed IP. These situations require elastic IPs.\n-\tElastic IPs are limited to 5 per account. It’s possible to [request more](https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-elastic-ips-ec2-classic).\n-\tIf an Elastic IP is not attached to an active resource there is a small [hourly fee](https://aws.amazon.com/ec2/pricing/on-demand/#Elastic_IP_Addresses).\n-\tElastic IPs are [no extra charge](https://aws.amazon.com/ec2/pricing/on-demand/#Elastic_IP_Addresses) as long as you’re using them. They have a (small) cost when not in use, which is a mechanism to prevent people from squatting on excessive numbers of IP addresses.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Elastic IP Gotchas and Limitations\n\n-\t🔸There is [officially no way](https://forums.aws.amazon.com/thread.jspa?threadID=171550) to allocate a contiguous block of IP addresses, something you may desire when giving IPs to external users. Though when allocating at once, you may get lucky and have some be part of the same CIDR block. If this is important to you, you may want to [bring your own IP](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html), which is more involved than this guide will go into.\n-\tUnofficially, if you have Enterprise support, you can ask your account rep to try to allocate a block of Elastic IPs with a business justification. For example, some of [Duo's fixed ranges](https://help.duo.com/s/article/1337?language=en_US) are [blocks of AWS IP space reassigned to `AWS-DUOSECURITYINC`](https://search.arin.net/rdap/?query=54.241.191.128). This is a best effort request, expect a denial. \n\nGlacier\n-------\n\n### Glacier Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/glacier/) ∙ [Developer guide](http://docs.aws.amazon.com/amazonglacier/latest/dev/) ∙ [FAQ](https://aws.amazon.com/glacier/faqs/) ∙ [Pricing](https://aws.amazon.com/glacier/pricing/)\n-\t**Glacier** is a lower-cost alternative to S3 when data is infrequently accessed, such as for archival purposes.\n-\tIt’s only useful for data that is rarely accessed. It generally takes [3-5 hours](https://aws.amazon.com/glacier/faqs/#dataretrievals) to fulfill a retrieval request.\n-\tAWS [has not officially revealed](https://en.wikipedia.org/wiki/Amazon_Glacier#Storage) the storage media used by Glacier; it may be low-spin hard drives or even tapes.\n-\tAWS has released an even more cost effective storate tier called [Glacier Deep Archive](https://aws.amazon.com/blogs/aws/new-amazon-s3-storage-class-glacier-deep-archive/) that offers ~12 hour retrieval latencies, but costs roughly a thousand dollars per month per petabyte.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Glacier Tips\n\n-\tYou can physically [ship](https://aws.amazon.com/blogs/aws/send-us-that-data/) your data to Amazon to put on Glacier on a USB or eSATA HDD.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Glacier Gotchas and Limitations\n\n-\t🔸Getting files off Glacier is glacially slow (typically 3-5 hours or more).\n-\t🔸Due to a fixed overhead per file (you pay per PUT or GET operation), uploading and downloading many small files on/to Glacier might be very expensive. There is also a 32k storage overhead per file. Hence it’s a good idea is to archive files before upload.\n-\t💸Be aware of the per-object costs of archiving S3 data to Glacier. [It costs $0.05 per 1,000 requests](https://aws.amazon.com/s3/pricing/). If you have large numbers of S3 objects of relatively small size, [it will take time to reach a break-even point](https://alestic.com/2012/12/s3-glacier-costs/) (initial archiving cost versus lower storage pricing).\n\nQuicksight\n----------\n\n### Quicksight Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/quicksight/) ∙ [User guide](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) ∙ [Pricing](https://aws.amazon.com/quicksight/pricing/)\n\n[Back to top :arrow_up:](#table-of-contents)\n### Quicksight Gotchas and Limitations\n\n-\t❗Out of the box Quicksight is not able to access tables that are linked to a Schema in the AWS Glue Schema Registry. This is because the auto-generated IAM role `aws-quicksight-service-role-v0` does not have the necessary permissions. You can't pick another role to be used but you can add more permissions to the role. The error message you will receive is an `SQL_EXCEPTION` with details `SYNTAX_ERROR: line 2:8: Column 'columnname' cannot be resolved` where `columnname` is the first column in your table.\n-\t🔸Only QuickSight accounts that were created in the US East (N. Virginia) region can access the QuickSight Forum/Community. And you can only have a QuickSight account in one region per AWS account.\n\nRDS\n---\n\n### RDS Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/rds/) ∙ [User guide](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/) ∙ [FAQ](https://aws.amazon.com/rds/faqs/) ∙ [Pricing](https://aws.amazon.com/rds/pricing/) (see also [ec2instances.info/rds/](http://www.ec2instances.info/rds/)\\)\n-\t**RDS** is a managed relational database service, allowing you to deploy and scale databases more easily. It supports [Oracle](https://aws.amazon.com/rds/oracle/), [Microsoft SQL Server](https://aws.amazon.com/rds/sqlserver/), [PostgreSQL](https://aws.amazon.com/rds/postgresql/), [MySQL](https://aws.amazon.com/rds/mysql/), [MariaDB](https://aws.amazon.com/rds/mariadb/), and Amazon’s own [Aurora](https://aws.amazon.com/rds/aurora/).\n-\tRDS offers out of the box support for [high availability and failover](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZ.html) for your databases.\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS Tips\n\n-\tIf you're looking for the managed convenience of RDS for other data stores such as MongoDB or Cassandra, you may wish to consider third-party services from providers such as [[Compose](https://www.compose.com/), or [InstaClustr](https://www.instaclustr.com/).\n-\t🔹Make sure to create a new [parameter group](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html) and option group for your database since the default parameter group does not allow dynamic configuration changes.\n-\tRDS instances start with a default timezone of UTC. If necessary, this can be [changed to a different timezone](https://aws.amazon.com/premiumsupport/knowledge-center/rds-change-time-zone/).\n-\tSave costs by stopping the RDS instance(s) when not in use, you can achieve this by configuring a stop and start schedule using the the [Instance Scheduler](https://aws.amazon.com/solutions/implementations/instance-scheduler/) solution.\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS Gotchas and Limitations\n\n-\t⏱RDS instances run on EBS volumes (either general-purpose or provisioned IOPS), and hence are constrained by EBS performance.\n-\t🔸Verify what database features you need, as not everything you might want is available on RDS. For example, if you are using Postgres, check the list of [supported features and extensions](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#SQLServer.Concepts.General.FeatureSupport). If the features you need aren't supported by RDS, you'll have to deploy your database yourself.\n-\t🔸If you use the failover support offered by RDS, keep in mind that it is based on DNS changes, and make sure that your client reacts to these changes appropriately. This is particularly important for Java, given how its DNS resolver’s TTL is [configured by default](http://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-jvm-ttl.html).\n-\t🔸**DB migration to RDS:** While importing your database into RDS ensure you take into consideration the maintenance window settings. If a backup is running at the same time, your import can take a considerably longer time than you would have expected.\n-\t[Database sizes are limited](https://aws.amazon.com/about-aws/whats-new/2015/06/amazon-rds-increases-storage-limits-to-6TB-for-piops-and-gp2/) to **6TB** for all database engines except for SQL Server which has a **4TB** limit and Aurora which supports up to **64TB** databases.\n\nRDS MySQL and MariaDB\n---------------------\n\n### RDS MySQL and MariaDB Basics\n\n-      RDS offers MySQL versions 5.5, 5.6, 5.7 and 5.8.\n-      RDS offers MariaDB versions 10.0, 10.1, 10.2 and 10.3.\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS MySQL and MariaDB Tips\n\n-\tMySQL RDS allows access to [binary logs](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_LogAccess.Concepts.MySQL.html#USER_LogAccess.MySQL.BinaryFormat).\n-\tMulti-AZ instances of MySQL transparently replicate data across AZs using DRBD. Automated backups of multi-AZ instances [run off the backup instance](https://www.percona.com/live/mysql-conference-2014/sessions/rds-mysql-tips-patterns-and-common-pitfalls) to reduce latency spikes on the primary.\n-\t🔸**Performance Schema:** While [Performance Schema](http://dev.mysql.com/doc/refman/en/performance-schema.html) is enabled by default in MySQL 5.6.6 and later, it is disabled by default in all versions of RDS. If you wish to enable Performance Schema, a reboot of the RDS instance will be required.\n-\t🔸**MySQL vs MariaDB vs Aurora:** If you prefer a MySQL-style database but are starting something new, you probably should consider Aurora and MariaDB as well. **Aurora** has increased availability and is the next-generation solution. That said, Aurora [may not be](http://blog.takipi.com/benchmarking-aurora-vs-mysql-is-amazons-new-db-really-5x-faster/) that much faster than MySQL for certain workloads. **MariaDB**, the modern [community fork](https://en.wikipedia.org/wiki/MariaDB) of MySQL, [likely now has the edge over MySQL](http://cloudacademy.com/blog/mariadb-vs-mysql-aws-rds/) for many purposes and is supported by RDS.\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS MySQL and MariaDB Gotchas and Limitations\n\n-\t🔸**No SUPER privileges.** RDS provides some [stored procedures](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.MySQL.SQLRef.html) to perform some tasks that require SUPER privileges such as starting or stopping replication.\n-\t🔸You can replicate to non-RDS instances of MySQL, but [replication to these instances will break during AZ failovers](https://www.percona.com/live/mysql-conference-2014/sessions/rds-mysql-tips-patterns-and-common-pitfalls).\n-\t🔸There is no ability to manually CHANGE MASTER on replicas, so they must all be rebuilt after a failover of the master.\n-\t🔸Most global options are exposed only via [DB parameter groups](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html). Some variables that were introduced in later MySQL dot releases such as [avoid_temporal_upgrade](https://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_avoid_temporal_upgrade) in MySQL 5.6.24 are not made available in RDS's 5.6.x parameter group and making use of them requires an upgrade to MySQL 5.7.x.\n-\t🔸RDS features such as Point-In-Time restore and snapshot restore are not supported on MyISAM tables. Ensure you lock and flush each MyISAM table before executing a snapshot or backup operation to ensure consistency.\n\nRDS PostgreSQL\n--------------\n\n### RDS PostgreSQL Basics\n\n- RDS offers PostgreSQL 9.3, 9.4, 9.5, 9.6, and 10.\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS PostgreSQL Tips\n- Recently Logical Replication is being supported, [both as subscriber and publisher](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#PostgreSQL.Concepts.General.version104).\n- Supports a relatively large range of native [extensions](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#PostgreSQL.Concepts.General.FeatureSupport.Extensions).\n- RDS PostgreSQL 10 Supports native partitioning and most of the major features and tunables.\n- Supports connections over SSL.\n- Supports multi A-Z and Point-in-time recovery.\n\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS PostgreSQL Gotchas and Limitations\n- No superuser privileges. RDS provides a role `rds_superuser` that can do most of the needed operations but there are some limitations.\n- Some major features are delayed compared to open source PostgreSQL.\n- By default RDS is spec’d with general purpose SSD , if you need better performance you have to spec provisioned IOPS SSD.\n- You can't use RDS as a replica outside RDS without using logical replication.\n- There are settings that cannot be changed and most of the settings that can change can only be changed using database parameter groups.\n- It’s harder to troubleshoot performance problems since you have no access to the host.\n- Be sure to verify that all the [extensions](https://www.postgresql.org/docs/current/static/view-pg-available-extensions.html) you need are available. If you are using an extension not listed there, you will need to come up with a work around, or deploy your own database in EC2.\n- Many Postgres utilities and maintenance items expect command line access, that can usually be satisfied by using an external ec2 server.\n\nRDS SQL Server\n--------------\n\n### RDS SQL Server Basics\n\n-\t[RDS offers SQL Server 2008 R2, 2012, 2014, 2016 and 2017](https://aws.amazon.com/rds/sqlserver/) including Express, Web, Standard and Enterprise.\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS SQL Server Tips\n\n-\tRecently added support for [backup and restore to/from S3](https://www.brentozar.com/archive/2016/07/holy-cow-amazon-rds-sql-server-just-changed-everything/) which may make it an attractive [DR option](https://aws.amazon.com/blogs/aws/amazon-rds-for-sql-server-support-for-native-backuprestore-to-amazon-s3/) for on-premises installations.\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS SQL Server Gotchas and Limitations\n\n-\t🔸The user is granted only db_owner privileges for each database on the instance.\n-\t🔸Storage cannot be expanded for existing databases. If you need more space, you must restore your database on a new instance with larger storage.\n-\t🔸There is a **16TB** database size limit for non-Express editions. There is also a minimum storage size, 20GB for Web and Express, 200GB for Standard and Enterprise.\n-\t🔸Limited to [30 databases per instance](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_SQLServer.html)\n\nRDS Aurora\n---\n### RDS Aurora Basics\nAurora is a cloud only database service designed to provide a distributed, fault-tolerant relational database with self-healing storage and auto-scaling up to 64TB per instance.  It currently comes in two versions, a MySQL compatible system, and a PostgreSQL compatible system.\n\nRDS Aurora MySQL\n----------------\n\n### RDS Aurora MySQL Basics\n\n-\tAmazon’s proprietary fork of MySQL intended to scale up for high concurrency workloads. Generally speaking, individual query performance under Aurora is not expected to improve significantly relative to MySQL or MariaDB, but Aurora is intended to maintain performance while executing many more queries concurrently than an equivalent MySQL or MariaDB server could handle.\n-\t[Notable new features](http://www.slideshare.net/AmazonWebServices/amazon-aurora-amazons-new-relational-database-engine) include:\n\t-\tLog-structured storage instead of B-trees to improve write performance.\n\t-\tOut-of-process buffer pool so that databases instances can be restarted without clearing the buffer pool.\n\t-\tThe underlying physical storage is a specialized SSD array that automatically maintains 6 copies of your data across 3 AZs.\n\t-\tAurora read replicas share the storage layer with the write master which significantly reduces replica lag, eliminates the need for the master to write and distribute the binary log for replication, and allows for zero-data-loss failovers from the master to a replica. The master and all the read replicas that share storage are known collectively as an **Aurora cluster**. Read replicas can span up to [5 regions](https://aws.amazon.com/about-aws/whats-new/2018/09/amazon-aurora-databases-support-up-to-five-cross-region-read-replicas/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS Aurora MySQL Tips\n\n-\tIn order to take advantage of Aurora’s higher concurrency, applications should be configured with large database connection pools and should execute as many queries concurrently as possible. For example, Aurora servers have been tested to produce increasing performance on some OLTP workloads with [up to 5,000 connections](http://www.slideshare.net/AmazonWebServices/amazon-aurora-amazons-new-relational-database-engine/31).\n-\t[Aurora scales well with multiple CPUs](https://www.percona.com/blog/2016/05/26/aws-aurora-benchmarking-part-2/) and may require a large instance class for optimal performance.\n-\tThe easiest migration path to Aurora is restoring a database snapshot from MySQL 5.6 or 5.7. The next easiest method is restoring a dump from a MySQL-compatible database such as MariaDB. For [low-downtime migrations](https://aws.amazon.com/blogs/aws/amazon-aurora-update-spatial-indexing-and-zero-downtime-patching/) from other MySQL-compatible databases, you can set up an Aurora instance as a replica of your existing database. If none of those methods are options, Amazon offers a fee-based data migration service.\n-\tYou can replicate [from an Aurora cluster to MySQL or to another Aurora cluster](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Aurora.Overview.Replication.MySQLReplication.html). This requires binary logging to be enabled and is not as performant as native Aurora replication.\n-\tBecause Aurora read replicas are the [equivalent of a multi-AZ backup](http://stackoverflow.com/a/32428651/129052) and they can be configured as zero-data-loss failover targets, there are fewer scenarios in which the creation of a multi-AZ Aurora instance is required.\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS Aurora MySQL Gotchas and Limitations\n\n- 🔸[Aurora 1.x is based on MySQL 5.6.x](https://news.ycombinator.com/item?id=12415693) with some cherry-picking of later MySQL features. It is missing most 5.7 features as well as some online DDL features introduced in 5.6.17.\n- 🔸[Aurora 2.x is based on MySQL 5.7.x](https://aws.amazon.com/about-aws/whats-new/2018/02/amazon-aurora-is-compatible-with-mysql-5-7/)\n- Aurora does not support GTID transactions in either the 5.6/Aurora 1.x or the 5.7/Aurora 2.x release lines.\n- Aurora maximum cluster size is 64 TB\n\nRDS Aurora PostgreSQL\n---------------------\n\n### RDS Aurora PostgreSQL Basics\n\n- Amazon’s proprietary fork of PostgreSQL, intended to scale up for high concurrency workloads while maintaining ease of use. Currently based on PostgreSQL 9.6.\n- Higher throughput (up to 3x with similar hardware).\n- Automatic storage scale in 10GB increments up to 64TB.\n- Low latency read replicas that share the storage layer with the master which significantly reduces replica lag.\n- Point in time recovery.\n- Fast database snapshots.\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS Aurora PostgreSQL Tips\n- Aurora Postgres by default is supposed to utilize high connection rates and for this reason connection pooling must be configured accordingly.\n- Because Aurora is based on PostgreSQL 9.6, it lacks features like declarative partitioning or logical replication.\n\n[Back to top :arrow_up:](#table-of-contents)\n### RDS Aurora PostgreSQL Gotchas and Limitations\n- Aurora PostgreSQL falls behind normal RDS when it comes to available versions, so if you need features from the latest PostgreSQL version you might be better off with plain RDS.\n- Patching and bug fixing is separate from open source PostgreSQL.\n\nElastiCache\n-----------\n\n### ElastiCache Basics\n\n- 📒 [Homepage](https://aws.amazon.com/elasticache/) ∙ [User\n  guide for Redis](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/index.html) ∙ [User\n  guide for Memcached](https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/index.html) ∙\n  [FAQ](https://aws.amazon.com/elasticache/faqs/) ∙\n  [Pricing](https://aws.amazon.com/elasticache/pricing/)\n- **ElastiCache** is a managed in-memory cache service, that can be used to\n  store temporary data in a fast in-memory cache, typically in order to avoid\n  repeating the same computation multiple times when it could be reused.\n- It supports both the [Memcached](https://memcached.org) and\n  [Redis](https://redis.io) open source in-memory cache software and exposes\n  them both using their native access APIs.\n- The main benefit is that AWS takes care of running, patching and optimizing\n  the cache nodes for you, so you just need to launch a cluster and configure\n  its endpoint in your application, while AWS will take of most of the operational\n  work of running the cache nodes.\n\n[Back to top :arrow_up:](#table-of-contents)\n### ElastiCache Tips\n\n- Choose the\n  [engine](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/SelectEngine.html),\n  clustering configuration and [instance\n  type](http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheNodes.SelectSize.html)\n  carefully based on your application needs. The documentation explains in\n  detail the pros, cons and limitations of each engine in order to help you\n  choose the best fit for your application. In a nutshell, Redis is\n  preferable for storing more complex data structures, while Memcached is just a\n  plain key/value store. The simplicity of Memcached allows it to be slightly\n  faster and allows it to scale out if needed, but Redis has more features which\n  you may use in your application.\n- For Memcached AWS provides enhanced SDKs for certain programming languages\n  which implement\n  [auto-discovery](https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/AutoDiscovery.html),\n  a feature not available in the normal memcached client libraries.\n\n[Back to top :arrow_up:](#table-of-contents)\n### ElastiCache Gotchas and Limitations\n\n- Since in some cases changing the cache clusters may have some restrictions,\n  like for\n  [scaling](http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Scaling.html)\n  purposes, it may become a problem if they were launched using CloudFormation\n  in a stack that also contains other resources and you really need to change\n  the cache. In order to avoid getting your CloudFormation stacks in a\n  non-updateable state, it is recommended to launch ElastiCache clusters (just\n  like any other resource with similar constraints) in dedicated stacks which\n  can be replaced entirely with new stacks having the desired configuration.\n\n\nDynamoDB\n--------\n\n### DynamoDB Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/dynamodb/) ∙ [Developer guide](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/) ∙ [FAQ](https://aws.amazon.com/dynamodb/faqs/) ∙ [Pricing](https://aws.amazon.com/dynamodb/pricing/)\n-\t**DynamoDB** is a [NoSQL](https://en.wikipedia.org/wiki/NoSQL) database with focuses on speed, flexibility, and scalability.\n-\tDynamoDB is priced on a combination of throughput and storage.\n\n[Back to top :arrow_up:](#table-of-contents)\n### DynamoDB Alternatives and Lock-in\n\n-\t⛓ Unlike the technologies behind many other Amazon products, DynamoDB is a proprietary AWS product with no interface-compatible alternative available as an open source project. If you tightly couple your application to its API and featureset, it will take significant effort to replace.\n-\tThe most commonly used alternative to DynamoDB is [Cassandra](http://cassandra.apache.org/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### DynamoDB Tips\n\n-\tThere is a [**local version of DynamoDB**](https://aws.amazon.com/blogs/aws/dynamodb-local-for-desktop-development/) provided for developer use.\n-\t[DynamoDB Streams](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) provides an ordered stream of changes to a table. Use it to replicate, back up, or drive events off of data\n-\tDynamoDB can be used [as a simple locking service](https://gist.github.com/ryandotsmith/c95fd21fab91b0823328).\n-\tDynamoDB indexing can include **primary keys**, which can either be a single-attribute hash key or a composite hash-key range. You can also query non-primary key attributes using [**secondary indexes**](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.html).\n-\t**Data Types:** DynamoDB supports three [data types](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.DataTypes.html) – **number**, **string**, and **binary** – in both scalar and multi-valued sets. DynamoDB can also support [**JSON**](https://aws.amazon.com/blogs/aws/dynamodb-update-json-and-more/).\n-\tAs of late 2017, DynamoDB supports both [global tables](https://aws.amazon.com/dynamodb/global-tables/) and [backup / restore functionality](https://aws.amazon.com/dynamodb/backup-restore/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### DynamoDB Gotchas and Limitations\n\n-\t🔸 DynamoDB doesn’t provide an easy way to bulk-load data (it is possible through [Data Pipeline](http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-importexport-ddb-part1.html)) and this has some [unfortunate consequences](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html#GuidelinesForTables.AvoidExcessivePTIncreases). Since you need to use the regular service APIs to update existing or create new rows, it is common to temporarily turn up a destination table’s write throughput to speed import. But when the table’s write capacity is increased, DynamoDB may do an irreversible split of the partitions underlying the table, spreading the total table capacity evenly across the new generation of tables. Later, if the capacity is reduced, the capacity for each partition is also reduced but the total number of partitions is not, leaving less capacity for each partition. This leaves the table in a state where it much easier for hotspots to overwhelm individual partitions.\n-\t🔸 It is important to make sure that DynamoDB [resource limits](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-data-types) are compatible with your dataset and workload. For example, the maximum size value that can be added to a DynamoDB table is 400 KB (larger items can be stored in S3 and a URL stored in DynamoDB).\n-\t🔸 Dealing with **time series data** in DynamoDB can be challenging. A global secondary index together with down sampling timestamps can be a possible solution as explained [here](https://blogs.aws.amazon.com/bigdata/post/Tx3KPZDXIBJEQ4B/Scaling-Writes-on-Amazon-DynamoDB-Tables-with-Global-Secondary-Indexes).\n-\t🔸 When setting up [fine grained policies](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/specifying-conditions.html) for access to DynamoDB tables, be sure to include their secondary indices in the policy document as well.\n\n\nECS\n---\n\n### ECS Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/ecs/) ∙ [Developer guide](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/) ∙ [FAQ](https://aws.amazon.com/ecs/faqs/) ∙ [Pricing](https://aws.amazon.com/ecs/pricing/)\n-\t**ECS** (EC2 Container Service) is a relatively new service (launched end of 2014) that manages clusters of services deployed via Docker.\n-\tSee the [Containers and AWS](#containers-and-aws) section for more context on containers.\n-\tECS is growing in adoption, especially for companies that embrace microservices.\n-\tDeploying Docker directly in EC2 yourself is another common approach to using Docker on AWS. Using ECS is not required, and ECS does not (yet) seem to be the predominant way many companies are using Docker on AWS.\n-\tIt’s also possible to use [Elastic Beanstalk with Docker](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_docker.html), which is reasonable if you’re already using Elastic Beanstalk.\n-\tUsing Docker may change the way your services are deployed within EC2 or Elastic Beanstalk, but it does not radically change how most other services are used.\n-\t[ECR](https://aws.amazon.com/ecr/) (EC2 Container Registry) is Amazon’s managed Docker registry service. While simpler than running your own registry, it is missing some features that might be desired by some users:\n\t-\tDoesn’t support cross-region replication of images.\n\t\t-\tIf you want fast fleet-wide pulls of large images, you’ll need to push your image into a region-local registry.\n\t-\tDoesn’t support custom domains / certificates.\n-\tA container’s health is monitored via [CLB](#clb) or [ALB](#alb). Those can also be used to address a containerized service. When using an ALB you do not need to handle port contention (i.e. services exposing the same port on the same host) since an ALB’s target groups can be associated with ECS-based services directly.\n-\t[The Hitchhikers Guide to AWS ECS and Docker](http://start.jcolemorrison.com/the-hitchhikers-guide-to-aws-ecs-and-docker/) by J. Cole Morrison is an excellent article for Introduction to AWS ECS concepts.\n\n\n\n[Back to top :arrow_up:](#table-of-contents)\n### ECS Tips\n\n-\t**Log drivers:** ECS supports multiple log drivers (awslogs, splunk, fluentd, syslog, json, ... ). Use [`awslogs`](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_awslogs.html) for CloudWatch (make sure a group is made for the logs first). [Drivers such as fluentd are not enabled by default](https://github.com/aws/amazon-ecs-agent/issues/535). You can, install the agent and enable the driver by adding `ECS_AVAILABLE_LOGGING_DRIVERS='[\"awslogs\",\"fluentd\"]'` to `/etc/ecs/ecs.config`.\n-\t[This blog from Convox](https://convox.com/blog/ecs-challenges) (and [commentary](https://news.ycombinator.com/item?id=11598058)) lists a number of common challenges with ECS as of early 2016.\n- It is possible to optimize disk clean up on ECS. By default, the unused containers are deleted after 3 hours and the unused images after 30 minutes. These settings can be changed by adding `ECS_ENGINE_TASK_CLEANUP_WAIT_DURATION=10m` and `ECS_IMAGE_CLEANUP_INTERVAL=10m` to `/etc/ecs/ecs.config`. [More information on optimizing ECS disk cleanup](https://aws.amazon.com/blogs/compute/optimizing-disk-usage-on-amazon-ecs/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### ECS Alternatives and Lock-in\n\n-\t[Kubernetes](https://kubernetes.io): Extensive container platform. Available as a hosted solution on [Google Cloud](https://cloud.google.com/kubernetes-engine), [AWS](https://aws.amazon.com/eks/), [Azure](https://azure.microsoft.com/en-us/services/kubernetes-service/), [DigitalOcean](https://www.digitalocean.com/products/kubernetes/), and [OpenShift](https://www.redhat.com/en/technologies/cloud-computing/openshift).\n-\t[Nomad](https://www.nomadproject.io/): Orchestrator/Scheduler, tightly integrated in the HashiCorp stack (Consul, Vault, etc).\n\n🚧 [*Please help expand this incomplete section.*](CONTRIBUTING.md)\n\nEKS\n---\n\n### EKS Basics\n-\t📒 [Homepage](https://aws.amazon.com/eks/) ∙ [User guide](http://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) ∙ [FAQ](https://aws.amazon.com/eks/faq/) ∙ [Pricing](https://aws.amazon.com/eks/pricing/)\n- EKS (Elastic Kubernetes Service) is a new service (launched June 2018) that provides managed Kubernetes Masters in a Highly Available pair to deploy K8s Services and Pods on top of EC2 based Kubernetes nodes.\n- See the [Containers and AWS](#containers-and-aws) section for more context on containers.\n- EKS is AWS's solution to hosting Kubernetes natively on AWS. It is not a replacement for ECS directly but is in response to the large market dominance of Kubernetes.\n- EKS does not launch EC2 nodes and would have to be configured and setup either manually or via Cloudformation (or other automation solution)\n- EKS management is done through a utility called kubectl, and with Kube configuration files. These files will need to be configured to speak with the K8s Master with a certificate and URL. The AWS CLI can autogenerate the configuration file that kubectl requires for communicating with the cluster.<sup>[1](#user-content-eks-aws-cli-create-kubeconfig)</sup>\n- EKS authentication is integrated with IAM roles/permissions. The AWS CLI has an integrated sub-command for generating authentication tokens.<sup>[2](#user-content-eks-aws-cli-get-token)</sup> This was formerly done via a custom plugin for kubectl called [aws-iam-authenticator](https://github.com/kubernetes-sigs/aws-iam-authenticator) (formerly heptio-authenticator-aws).\n- EKS provides [Calico](https://docs.aws.amazon.com/eks/latest/userguide/calico.html) from Tigera for securing workloads within a cluster using Kubernetes network policy.\n\n[Back to top :arrow_up:](#table-of-contents)\n### EKS Tips\n- Multiple clusters can be supported by using different kubeconfig files.\n- AWS has a [Kubernetes Quickstart](https://aws.amazon.com/quickstart/architecture/heptio-kubernetes/) developed in collaboration with Heptio.\n\n[Back to top :arrow_up:](#table-of-contents)\n### EKS Alternatives and Lock-in\n- [ECS](#ecs): Amazon's native Container Scheduled platform released in 2014.  If you don't utilise containers today and are looking to get started, ECS is an excellent product.\n-\t[Kubernetes](https://kubernetes.io): Extensive container platform. Available as a hosted solution on [Google Cloud](https://cloud.google.com/container-engine/), [AWS](https://aws.amazon.com/eks/), [Digital Ocean](https://www.digitalocean.com/products/kubernetes/) and [Azure](https://azure.microsoft.com/en-us/services/kubernetes-service/).\n-\t[Nomad](https://www.nomadproject.io/): Orchestrator/Scheduler, tightly integrated in the HashiCorp stack (Consul, Vault, etc).\n\n[Back to top :arrow_up:](#table-of-contents)\n### EKS Gotchas and Limitations\n- Pods and Service configurations can rapidly consume IP addresses inside a VPC.  Proper care and maintenance should be applied to ensure IP exhaustion does not occur.\n- There is currently no integrated monitoring in CloudWatch for EKS pods or services, you will need to deploy a monitoring system that supports Kubernetes such as Prometheus.\n- Autoscaling based off CPU/Memory of a node is limited as you will not be aware of pending Services/Pods that cannot start. Using [cluster-autoscaler](https://github.com/kubernetes/autoscaler/tree/master/cluster-autoscaler) can be useful for scaling based on Node resource usage and unschedulable Pods.\n- [Prometheus](https://prometheus.io/) is a very popular monitoring solution for K8s, metrics and alerts can be used to send events to Lambda, SQS or other solutions to take autoscaling actions.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Footnotes\n<a name=\"user-content-eks-aws-cli-create-kubeconfig\">**1**</a>: https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html<br />\n<a name=\"user-content-eks-aws-cli-get-token\">**2**</a>: https://aws.amazon.com/about-aws/whats-new/2019/05/amazon-eks-simplifies-kubernetes-cluster-authentication/<br />\n\nFargate\n-------\n\n### Fargate Basics\n-\t📒 [Homepage](https://aws.amazon.com/fargate/) ∙ [FAQ](https://aws.amazon.com/fargate/faqs/) ∙ [Pricing](https://aws.amazon.com/fargate/pricing/)\n-   **Fargate** allows you to manage and deploy containers without having to worry about running the underlying compute infrastructure\n-   Fargate serves as a new backend (in addition to the legacy EC2 backend) on which ECS and EKS tasks can be run\n-   Fargate and EC2 backends are called \"Launch Types\"\n-   Fargate allows you to treat containers as fundamental building blocks of your infrastructure\n\n[Back to top :arrow_up:](#table-of-contents)\n### Fargate Tips\n-   Fargate follows a similar mindset to Lambda, which lets you focus on applications, instead of dealing with underlying infrastructure\n-   Fargate is supported by CloudFormation, aws-cli and ecs-cli\n-   Fargate tasks can be launched alongside tasks that use EC2 Launch Type\n-   💸Before creating a large Fargate deployment, make sure to estimate costs and compare them against alternative solution that uses traditional EC2 deployment - Fargate prices can be several times those of equivalently-sized EC2 instances. To evaluate both solutions based on potential costs, refer to pricing for [EC2](https://aws.amazon.com/ec2/pricing/) and [Fargate](https://aws.amazon.com/fargate/pricing/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### Fargate Alternatives and Lock-in\n-   🚪[Azure Container Instances](https://azure.microsoft.com/en-us/services/container-instances/): Available on Microsoft Azure in preview version, allows to run applications in containers without having to manage virtual machines\n\n[Back to top :arrow_up:](#table-of-contents)\n### Fargate Gotchas and Limitations\n-   The smallest resource values that can be configured for an ECS Task that uses Fargate is 0.25 vCPU and 0.5 GB of memory\n-   [Task storage is ephemeral. After a Fargate task stops, the storage is deleted.](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/fargate-task-storage.html)\n\n\nLambda\n------\n\n### Lambda Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/lambda/) ∙ [Developer guide](http://docs.aws.amazon.com/lambda/latest/dg/) ∙ [FAQ](https://aws.amazon.com/lambda/faqs/) ∙ [Pricing](https://aws.amazon.com/lambda/pricing/)\n-\t**Lambda** is AWS' serverless compute offering, allowing users to define Lambda functions in a selection of runtimes that can be invoked via a variety of triggers, including SNS notifications and API Gateway invocations. Lambda is the key service that enables ['serverless' architecture on AWS](https://aws.amazon.com/lambda/serverless-architectures-learn-more/), alongside AWS API Gateway, AWS Batch, and AWS DynamoDB.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Lambda Tips\n\n-\tThe idea behind 'serverless' is that users don't manage provisioning, scaling, or maintenance of the physical machines that host their application code. With Lambda, the machine that actually executes the user-defined function is abstracted as a ['container'](http://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html). When defining a Lambda function, users are able to declare the amount of memory available to the function, which directly affects the physical hardware specification of the Lambda container.\n-\tChanging the amount of memory available to your Lambda functions also affects the amount of [CPU power](https://aws.amazon.com/lambda/faqs/) available to it.\n-\tWhile AWS does not offer hard guarantees around container reuse, in general it can be expected that an unaltered Lambda function will reuse a warm (previously used) container if called shortly after another invocation. Users can use this as a way to optimize their functions by smartly caching application data on initialization.\n-\tA Lambda that hasn't been invoked in some time may not have any warm containers left. In this case, the Lambda system will have to load and initialize the Lambda code in a 'cold start' scenario, which can add significant latency to Lambda invocations.  Lambda cold start performance [has improved significantly over the 2018-2019 timeframe](https://levelup.gitconnected.com/aws-lambda-cold-start-language-comparisons-2019-edition-%EF%B8%8F-1946d32a0244) and is now typically in the range of 200-500 ms for a simple function depending on the language runtime.\n-\tLambda functions running insides of VPCs have also seen [recent improvements](https://aws.amazon.com/blogs/compute/announcing-improved-vpc-networking-for-aws-lambda-functions/) to cold start times.  Previously these VPC-hosted functions would have cold starts of ~15 seconds; now those same functions cold start in < 1 second.\n-\tThere are a few strategies to avoiding or mitigating cold starts.  [Provisioned concurrency](https://aws.amazon.com/blogs/aws/new-provisioned-concurrency-for-lambda-functions/) was announced at re:invent 2019 and is an effective means to eliminating cold starts. Other techniques include keeping containers warm by periodic triggering and favoring lightweight runtimes such as Node as opposed to Java.\n-\tLambda is integrated with AWS CloudWatch and provides a logger at runtime that publishes CloudWatch events.\n-\tLambda offers out-of-the-box opt-in support for AWS X-Ray. X-Ray can help users diagnose Lambda issues by offering in-depth analysis of their Lambda's execution flow. This is especially useful when investigating issues calling other AWS services as X-Ray gives you a detailed and easy-to-parse [visualization of the call graph](http://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html#lambda-service-map).\n-\tUsing [timed CloudWatch events](http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html#CronExpressions), users can use Lambda to run periodic jobs in a cron-like manner.\n-\tEvents sent to Lambda that fail processing can be managed using a [Dead Letter Queue (DLQ) in SQS.](http://docs.aws.amazon.com/lambda/latest/dg/dlq.html)\n-\tMore on serverless:\n\t-\t[Mike Roberts's thoughts on martinfowler.com.](http://martinfowler.com/articles/serverless.html)\n\t-\t[AWS Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model), a simplification built on top of CloudFormation that can help to define, manage, and deploy serverless applications using Lambda.\n\t-\t[Serverless](https://github.com/serverless/serverless), one of the most popular frameworks for building serverless applications using AWS Lambda and other serverless compute options.\n\t-\t[Other helpful frameworks.](https://github.com/anaibol/awesome-serverless#frameworks)\n\n[Back to top :arrow_up:](#table-of-contents)\n### Lambda Alternatives and Lock-in\n\n-\t🚪Other clouds offer similar services with different names, including [Google Cloud Functions](https://cloud.google.com/functions/), [Azure Functions](https://azure.microsoft.com/en-us/services/functions/), and [IBM OpenWhisk](http://www.ibm.com/cloud-computing/bluemix/openwhisk/). Also if you are running Kubernetes another Lambda alternative is [OpenFaaS](https://github.com/openfaas/faas)\n\n[Back to top :arrow_up:](#table-of-contents)\n### Lambda Gotchas and Limitations\n\n- 🔸Testing Lambdas, locally and remotely, can be a challenge. Several tools are available to make this easier, including the officially supported [SAM Local](https://github.com/awslabs/aws-sam-local).\n- 🔸Managing lots of Lambda functions is a workflow challenge, and tooling to manage Lambda deployments is still immature.\n- 🔸AWS’ official workflow around managing function [versioning and aliases](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html) is painful. One option is to avoid Lambda versioning by abstracting your deployment workflow outside of Lambda. One way this can be accomplished is by deploying your application in successive stages, with a distinct AWS account per stage, where each account only needs to be aware of the latest version, and rollbacks and updates are handled by external tooling.\n- 🔸While adding/removing S3 buckets as triggers for Lambda function, this error may occur: \"There was an error creating the trigger: Configuration is ambiguously defined. Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type.\" In this case, you can manually remove the Lambda event in the \"Events\" tab in the \"Properties\" section of the S3 bucket.\n- 🔸Managing the size of your deployment artifact can be a challenge, especially if using Java. Options to mitigate this include [proguard](https://www.guardsquare.com/en/proguard) and loading dependencies at runtime into /tmp.\n- When using DynamoDB as a trigger for your Lambda functions, this error may occur: \"PROBLEM: internal Lambda error. Please contact Lambda customer support.\" This usually just means that Lambda can't detect anything in the DynamoDB stream within the last 48 hours. If the issue persists, deleting and recreating your trigger may help.\n- 🔸If your lambda needs access to resources in a VPC (for example ElastiCache or RDS), it will need to be deployed within it. This will increase cold-start times as an Elastic Network Interface (ENI) will have to be registered within the VPC for each concurrent function. AWS also has a relatively low initial limit (350) on the number ENI's that can be created within an VPC, however this can be increased to the 1000s if a good case is made to AWS support.\n- 🔸If your lambda is in a VPC and needs access to resources outside VPC such outbound internet access, it will need a NAT gateway associated even if it is in public subnet. Lambdas won't be assigned a public IP irrespective of subnet. If it is accessing AWS services (for example S3), you may use VPC endpoints.\n-\t🔸 Lambda has several [**resource limits**](http://docs.aws.amazon.com/lambda/latest/dg/limits.html) as of 2017-06:\n\t-\tA **6MB** request or response payload size.\n\t-\tA **50 MB** limit on the compressed .zip/.jar file deployment package size.\n\t-\tA **250 MB** limit on the code/dependencies in the package before compression.\n\t- A **500 MB** limit on local storage in /tmp.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Lambda Code Samples\n\n-\t[Fan-out](https://github.com/awslabs/aws-lambda-fanout) is an example of using Lambda to “fan-out” or copy data from one service, in this case Kinesis, to multiple other AWS data services. Destinations for fan-out data in the sample include IoT, SQS and more.\n-\tThis [AWS limit monitor using Lambdas](https://github.com/awslabs/aws-limit-monitor) shows use of multiple Lambdas for monitoring.\n-\tThis [Lambda ECS Worker Pattern](https://github.com/awslabs/lambda-ecs-worker-pattern) shows use of Lambda in a workflow where data from S3 is picked up by the Lambda, pushed to a queue, then sent to ECS for more processing.\n-\tThe [Secure Pet Store](https://github.com/awslabs/api-gateway-secure-pet-store) is a sample Java application which uses Lambda and API Gateway with Cognito (for user identity).\n-\t[aws-lambda-list](https://github.com/unixorn/aws-lambda-list) is a list of \"hopefully useful AWS lambdas and lambda-related resources\". Quite a few code samples here; as usual, not guaranteed tested. Caveat Emptor.\n\n🚧 [*Please help expand this incomplete section.*](CONTRIBUTING.md)\n\nAPI Gateway\n-----------\n\n### API Gateway Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/api-gateway/) ∙ [Developer guide](http://docs.aws.amazon.com/apigateway/latest/developerguide/) ∙ [FAQ](https://aws.amazon.com/api-gateway/faqs/) ∙ [Pricing](https://aws.amazon.com/api-gateway/pricing/)\n-\t**API Gateway** provides a scalable, secured front-end for service APIs, and can work with Lambda, Elastic Beanstalk, or regular EC2 services.\n-\tIt allows “serverless” deployment of applications built with Lambda.\n-\t🔸Switching over deployments after upgrades can be tricky. There are no built-in mechanisms to have a single domain name migrate from one API gateway to another one. So it may be necessary to build an additional layer in front (even another API Gateway) to allow smooth migration from one deployment to another.\n\n[Back to top :arrow_up:](#table-of-contents)\n### API Gateway Alternatives and Lock-In\n\n- [Kong](https://getkong.org) is an open-source, on-premises API and microservices gateway built on nginx with Lua. Kong is extensible through “plugins”.\n- [Tyk](https://tyk.io) is an open-source API gateway implemented in Go and available in the cloud, on-premises or hybrid.\n\n[Back to top :arrow_up:](#table-of-contents)\n### API Gateway Tips\n\n-\t🔹Prior to 2016-11, you could only send and receive plain text data (so people would base64-encode binary data), but binary data is [now](https://aws.amazon.com/about-aws/whats-new/2016/11/binary-data-now-supported-by-api-gateway/) supported.\n-\tAPI Gateway supports the OpenApi specification (aka [Swagger](https://swagger.io/)). This allows you to describe your API in a language-agnostic way and use various tools to generate code supporting your API.\n-\tGenerating clients is extremely easy, either through the AWS console or using the get-sdk API.\n-\tAPI Gateway integrates with CloudWatch out-of-the-box, allowing for easy logging of requests and responses.\n\t-\tNote that if your request or response are too large, CloudWatch will truncate the log. For full request/reply logging, make sure to do so in your integration (e.g. Lambda).\n\t-\tA good practice when calling API Gateway APIs is to log the request ID on the client. You can later refer to these request IDs in CloudWatch for easier tracing and debugging.\n-\tThere are multiple ways to secure your API, including built-in support for [AWS Cognito](http://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html). For most use-cases, Cognito is the easiest and simplest way to authenticate users.\n\t-\tAlthough you can roll your own solution using a [custom authorizer](http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html), which is basically a Lambda you define that determines if a request is acceptable or not.\n-\tWhile API Gateway lends itself well to REST-style development, it's perfectly reasonable to implement an RPC-style API in API Gateway as well. Depending on your use-case, this can often lead to a much simpler API structure and smoother client experience.\n\t-\tRPC-style APIs are particularly useful when designing services that sit deeper in the stack and don't serve content directly to users.\n\n\n[Back to top :arrow_up:](#table-of-contents)\n### API Gateway Gotchas and Limitations\n\n-\t🔸API Gateway only supports encrypted (https) endpoints, and does not support unencrypted HTTP. (This is probably a good thing.)\n-\t🔸API Gateway doesn’t support multi-region deployments for high availability. It is a service that is deployed in a single region but comes with a global endpoint that is served from AWS edge locations (similar to a CloudFront distribution). You cannot have multiple API Gateways with the same hostname in different AWS regions and use Route 53 to distribute the traffic. More in [this forum post](https://forums.aws.amazon.com/thread.jspa?messageID=735342&#735342).\n- 🔸Integration timeout: All of the various integration types (eg: Lambda, HTTP) for API Gateway have timeouts, as described [here](http://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#api-gateway-limits). Unlike some limits, these timeouts can't be increased.\n- 🔸API Gateway returns a 504 status code for any network or low level transport related issue. When this happens, you may see a message in the CloudWatch logs for the request that includes the message: `Execution failed due to an internal error`. One possible reason for this error is that even though your backend server is up and running, it may be doing something outside of the HTTP specification (like not sending well-formed chunked messages). You can test by hitting your backend directly with the `curl --raw -S -i <backend-endpoint-url>` and seeing if it complains.\n-\t🔸AWS X-Ray support exists but cumbersome to use. If you have other AWS services calling API Gateway, your trace will seemingly end there. API Gateway will also not appear as a node in your service map. [More here](http://docs.aws.amazon.com/xray/latest/devguide/xray-services-apigateway.html).\n-\t🔸Be careful using the export feature. The resulting Swagger template is often incomplete and doesn't integrate well with the Swagger extensions for things such as CORS.\n-\t🔸Many changes to API Gateway resources need to be 'deployed' via console or API call. Unfortunately, API Gateway is terrible about notifying the user when changes are staged for deployment and what changes require deployment. If you've changed something about your API and it's not taking effect, there's a decent chance you just need to deploy it.\n\t-\tIn particular, when deploying an API Gateway as part of a CloudFormation stack, changes will not automatically deploy unless the deployment resource itself was changed. You can change work around this by always changing the deployment resource on a CloudFormation update, or running a custom resource that ensures the deployment is made.\n\t-\tAlternatively, by using the [Serverless Application Model](https://github.com/awslabs/serverless-application-model) definition for an API Gateway resource, you can always expect the API to be deployed on a stack update since SAM will generate a new deployment every time.\n- 🔸API Gateway does not support nested query parameters on method requests.\n- 🔸API Gateway limits number of resources to 300, as described [here](http://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#api-gateway-limits). This is something to be considered when you start using API Gateway as a platform where your team/organization deploys to the same API Gateway.\n\n🚧 [*Please help expand this incomplete section.*](CONTRIBUTING.md)\n\nStep Functions\n------\n\n### Step Functions Basics\n-\t📒 [Homepage](https://aws.amazon.com/step-functions/) ∙ [Developer guide](http://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) ∙ [FAQ](https://aws.amazon.com/step-functions/faqs/) ∙ [Pricing](https://aws.amazon.com/step-functions/pricing/)\n-\t**Step Functions** is AWS’ way to create state machines that manage a serverless workflow.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Step Functions Tips\n-   A variety of structures are supported including branching, parallel operations and waits\n-   [Tasks](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-tasks.html) represent the real work nodes and are frequently Lambda functions, but can be [Activities](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-activities.html) which are externally driven tasks implemented any way you like.\n-   State machines have [data](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-state-machine-data.html) that \"flows\" through the steps and can be modified and added to as the state machine executes.\n-   It's best if your tasks are idempotent, in part because you may want to re-run the state machine with the same input data during debugging\n-   The AWS Console facilitates your examining the execution state at various steps.\n    -   The console lets you do this with a few steps:\n        -   select the \"input\" tab from the failed execution\n        -   copy the input data (JSON)\n        -   select the state machine name in the breadcrumbs\n        -   start a new execution, pasting the input data you copied previously\n\n[Back to top :arrow_up:](#table-of-contents)\n### Step Functions Gotchas and Limitations\n-   Step Functions are free tier eligible up to an initial 4000 transitions per month. Thereafter, the charge is $0.025 per 1000 state transitions.\n-   You can have many, simultaneous, executions, but be aware of lambda throttling limits. This has been per-account, pre-region, but recently became settable per-lambda.\n-   Step Function executions are limited to 25,000 events. Each step creates multiple events. This means that [iterating a loop using Lambda](https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-create-iterate-pattern-section.html) is limited to an iteration count of around 3000 before needing to [continue as a new execution](https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-continue-new.html).\n\nRoute 53\n--------\n\n### Route 53 Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/route53/) ∙ [Developer guide](http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/) ∙ [FAQ](https://aws.amazon.com/route53/faqs/) ∙ [Pricing](https://aws.amazon.com/route53/pricing/)\n-\t**Route 53** is AWS’ DNS service.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Route 53 Alternatives and Lock-In\n\n-\tHistorically, AWS was slow to penetrate the DNS market (as it is often driven by perceived reliability and long-term vendor relationships) but Route 53 has matured and [is becoming the standard option](https://www.datanyze.com/market-share/dns/) for many companies. Route 53 is cheap by historic DNS standards, as it has a fairly large global network with geographic DNS and other formerly “premium” features. It’s convenient if you are already using AWS.\n-\t⛓Generally you don’t get locked into a DNS provider for simple use cases, but increasingly become tied in once you use specific features like geographic routing or Route 53’s alias records.\n-\t🚪Many alternative DNS providers exist, ranging from long-standing premium brands like [UltraDNS](https://www.neustar.biz/services/dns-services) and [Dyn](http://dyn.com/managed-dns/) to less well known, more modestly priced brands like [DNSMadeEasy](http://www.dnsmadeeasy.com/). Most DNS experts will tell you that the market is opaque enough that reliability and performance don’t really correlate well with price.\n-\t⏱Route 53 is usually somewhere in the middle of the pack on performance tests, e.g. the [SolveDNS reports](http://www.solvedns.com/dns-comparison/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### Route 53 Tips\n\n-\t🔹Know about Route 53’s “alias” records:\n\t-\tRoute 53 supports all the standard DNS record types, but note that [**alias resource record sets**](http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-choosing-alias-non-alias.html) are not standard part of DNS, but a specific Route 53 feature. (It’s available from other DNS providers too, but each provider has a different name for it.)\n\t-\tAliases are like an internal name (a bit like a CNAME) that is resolved internally on the server side. For example, traditionally you could have a CNAME to the DNS name of a CLB or ALB, but it’s often better to make an alias to the same load balancer. The effect is the same, but in the latter case, externally, all a client sees is the target the record points to.\n\t-\tIt’s often wise to use alias record as an alternative to CNAMEs, since they can be updated instantly with an API call, without worrying about DNS propagation.\n\t-\tYou can use them for CLBs/ALBs or any other resource where AWS supports it.\n\t-\tSomewhat confusingly, you can have CNAME and A aliases, depending on the type of the target.\n\t-\tBecause aliases are extensions to regular DNS records, if exported, the output [zone file](https://en.wikipedia.org/wiki/Zone_file) will have additional non-standard “ALIAS” lines in it.\n-\t[**Latency-based routing**](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html#routing-policy-latency) allows users around the globe to be automatically directed to the nearest AWS region where you are running, so that latency is reduced.\n-\tUnderstand that domain registration and DNS management (hosted zones) are two separate Route 53 services. When you buy/transfer a domain, Route 53 automatically assigns four name servers to it (e.g. ns-2.awsdns-00.com). Route 53 also offers to automatically create a hosted zone for DNS management, but you are not required do your DNS management in the same account or even in Route 53; you just need to create an NS record pointing to the servers assigned to your domain in Route 53.\n  - One use case would be to put your domain registration (very mission critical) in a [bastion account](https://cloudonaut.io/your-single-aws-account-is-a-serious-risk/) while managing the hosted zones within another account which is accessible by your applications.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Route 53 Gotchas and Limitations\n-   🔸Private Hosted Zone will only respond to DNS queries that originate from within a VPC. As a result Route53 will not respond to request made via a VPN or Direct connect. To get around this you will need to implement [Hybrid Cloud DNS Solutions](https://d1.awsstatic.com/whitepapers/hybrid-cloud-dns-options-for-vpc.pdf) or use the Simple AD provided IP addresses to query the hosted zone.\n\n\nCloudFormation\n--------------\n\n### CloudFormation Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/cloudformation/) ∙ [Developer guide](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/) ∙ [FAQ](https://aws.amazon.com/cloudformation/faqs/) ∙ [Pricing](https://aws.amazon.com/cloudformation/pricing/) at no additional charge\n-\t**CloudFormation** allows you to manage sets of resources from other AWS services grouped into **[stacks](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html#d0e3917)**. CloudFormation allows you to define these stacks in a template using [JSON](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#aws-properties-ec2-instance-syntax.json) or [YAML](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#aws-properties-ec2-instance-syntax.yaml). CloudFormation is one of the major services underpinning AWS' [infrastructure as code capabilities](https://d0.awsstatic.com/whitepapers/DevOps/infrastructure-as-code.pdf) and is crucial in enabling repeatable and consistent deployments of infrastructure.\n-\t💸CloudFormation itself has [no additional charge](https://aws.amazon.com/cloudformation/pricing/); you pay for the underlying resources.\n\n[Back to top :arrow_up:](#table-of-contents)\n### CloudFormation Alternatives and Lock-In\n\n-\tHashiCorp’s [Terraform](https://www.\n/intro/vs/cloudformation.html) is a third-party alternative that can support other cloud platforms/providers including [Azure](https://registry.terraform.io/providers/hashicorp/azurerm/latest) and [OpenStack](https://www.terraform.io/docs/providers/openstack/).\n- 🔸Some AWS features may not be available in Terraform (e.g. multi-AZ ElastiCache using Redis), and you may have to resort to embedded CloudFormation templates.\n-\t[Pulumi](https://www.pulumi.com/) enables teams to define and deliver Cloud Native Infrastructure as Code on any cloud, with any language. From containers to serverless to Kubernetes to infrastructure.\n\n[Back to top :arrow_up:](#table-of-contents)\n### CloudFormation Tips\n\n-\tValidate your stack in a different AWS account! CloudFormation truly shines when making multiple deployments of the same stack to different accounts and regions. A common practice is to deploy stacks in successive stages ending in a production rollout.\n-\tAvoid potentially time-consuming syntax errors from eating into your deployment time by running `validate-template`.\n-\tCloudFormation is sometimes slow to update what resources (and new features on old services) a user is able to define in the template. If you need to deploy a resource or feature that isn't supported by the template, CloudFormation allows running arbitrary code (using [Lambda](#lambda)) on a stack create or update via [custom resources](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html).\n-\tCustom resources make CloudFormation into a truly powerful tool, as you can do all sorts of neat things quite easily such as sanity tests, initial configuration of Dynamo tables or S3 buckets, cleaning up old CloudWatch logs, etc.\n\t- For writing Custom Resources in Javascript, AWS provides a good reference in the [documentation.](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-custom-resources-lambda-lookup-amiids.html)\n-\tCloudFormation offers a visual [template designer](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/working-with-templates-cfn-designer-walkthrough-createbasicwebserver.html) that can be useful when getting up to speed with the template syntax.\n-\tBy using [StackSets](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-concepts.html), users can define and deploy an entire production application consisting of multiple stacks (one service per stack) in a single CloudFormation template.\n-\tIf you're developing a serverless application (i.e., using Lambda, API Gateway) CloudFormation offers a simplified template format called [SAM](https://github.com/awslabs/serverless-application-model).\n-\t❗Use a restrictive [stack policy](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html)! Without one, you can inadvertently delete live production resources, probably causing a severe outage.\n-\t❗Turn on [termination protection](https://aws.amazon.com/about-aws/whats-new/2017/09/aws-cloudformation-provides-stack-termination-protection/) on all of your stacks to avoid costly accidents!\n-\tThe CloudFormation [template reference](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-reference.html) is indispensable when discovering what is and isn't possible in a CloudFormation template.\n-\t[Troposphere](https://github.com/cloudtools/troposphere) is a Python library that makes it much easier to create CloudFormation templates.\n\t- Currently supports [AWS](https://github.com/cloudtools/troposphere#currently-supported-aws-resource-types) and [OpenStack](https://github.com/cloudtools/troposphere#currently-supported-openstack-resource-types) resource types.\n\t- Troposphere attempts to support all resources types that can be described in CloudFormation templates.\n\t- Built in [error](https://github.com/cloudtools/troposphere#examples-of-the-error-checking-full-tracebacks-removed-for-clarity) checking.\n\t- A recommended soft dependency is [awacs](https://github.com/cloudtools/awacs), which allows you to generate AWS access policy in JSON by writing Python code.\n-\t[stacker](http://stacker.readthedocs.io/en/latest/) is a Python application that makes it easy to define, configure, orchestrate and manage dependencies for CloudFormation stacks across multiple user-defined environments.\n-\tIf you are building different stacks with similar layers, it may be useful to build separate templates for each layer that you can reuse using [AWS::CloudFormation::Stack](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html).\n-\t🔸Avoid hardcoding resource parameters that can potentially change. Use stack parameters as much as you can, and resort to default parameter values.\n-\t🔹Until [2016](https://aws.amazon.com/about-aws/whats-new/2016/09/aws-cloudformation-introduces-yaml-template-support-and-cross-stack-references/), CloudFormation used only an awkward JSON format that makes both reading and debugging difficult. To use it effectively typically involved building additional tooling, including converting it to YAML, but now [this is supported directly](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-formats.html).\n- Wherever possible, export relevant [physical IDs](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) from your Stacks by defining [Outputs in your CloudFormation Templates](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html). These are the actual names assigned to the resources being created. Outputs can be returned from `DescribeStack` API calls, and get imported to other Stacks as part of the [recent addition](https://aws.amazon.com/about-aws/whats-new/2016/09/aws-cloudformation-introduces-yaml-template-support-and-cross-stack-references/) of [cross-stack references](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-crossstackref.html).\n\t-Note that importing outputs in a stack from another stack creates a hard dependency that is tracked by CloudFormation. You will not be able to delete the stack with the outputs until there are no importing stacks.\n-\tCloudFormation can be set up to [send SNS notifications](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-add-tags.html) upon state changes, enabling programmatic handling of situations where stacks fail to build, or simple email alerts so the appropriate people are informed.\n-\tCloudFormation allows the use of [**conditionals**](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) when creating a stack.\n\t-\tOne common way to leverage this capability is in support of multi-environment CloudFormation templates – by configuring them to use ‘if-else’ statements on the value of a [parameter passed in](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) (e.g.  “env”), environment-specific values for things like VPC IDs, SecurityGroup IDs, and AMI names can be passed into reusable generic templates.\n-\t**Version control your CloudFormation templates!** In the Cloud, an application is the combination of the code written and the infrastructure it runs on. By version controlling **both**, it is easy to roll back to known good states.\n-\tAvoid naming your resources explicitly (e.g. DynamoDB tables). When deploying multiple stacks to the same AWS account, these names can come into conflict, potentially slowing down your testing. Prefer using resource references instead.\n-\tFor things that shouldn't ever be deleted, you can set an explicit DeletionPolicy on the resource that will prevent the resource from being deleted even if the CloudFormation stack itself is deleted. This is useful for anything that can maintain expensive-to-rebuild state, such as DynamoDB tables, and things that are exposed to the outside world, such as API Gateway APIs.\n\n[Back to top :arrow_up:](#table-of-contents)\n### CloudFormation Gotchas and Limitations\n\n-\t🔸A given CloudFormation stack can end up in a wide variety of states. Error reporting is generally weak, and often times multiple observe-tweak-redeploy cycles are needed to get a working template. The internal state machine for [all the varying states](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html) is extremely opaque.\n-\t🔸Some cross-region operations are not possible in CloudFormation without using a custom resource, such as [cross-region SNS subscriptions](https://github.com/serverless/serverless/issues/3676).\n-\t🔸While having hand-made resources live alongside CloudFormation-created resources is inadvisable, it's sometimes unavoidable. If at all possible, leave ALL resource management up to a CloudFormation template and only provide read-only access to the console.\n-\t❗Modifications to stack resources made outside CloudFormation can potentially lead to stacks stuck in UPDATE\\_ROLLBACK\\_FAILED mode. Stacks in this state can be recovered using the [continue-update-rollback command](https://aws.amazon.com/blogs/devops/continue-rolling-back-an-update-for-aws-cloudformation-stacks-in-the-update_rollback_failed-state/). This command can be initiated in the console or in the CLI. The [--resources-to-skip](http://docs.aws.amazon.com/cli/latest/reference/cloudformation/continue-update-rollback.html) parameter usable in the CLI can be useful if the continue-update-rollback command fails. New feature [Drift Detection](https://aws.amazon.com/blogs/aws/new-cloudformation-drift-detection/) can be used to detect outside changes made to stack.\n-\t🔸CloudFormation is useful but complex and with a variety of pain points. Many companies find alternate solutions, and many companies use it, but only with significant additional tooling.\n-\t🔸CloudFormation can be very slow, especially for items like CloudFront distributions and Route53 CNAME entries.\n-\t🔸It’s hard to assemble good CloudFormation configurations from existing state. AWS does [offer a trick to do this](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-using-cloudformer.html), but it’s very clumsy.\n\t- CloudFormer also hasn't been updated in ages (as of Oct 2017), doesn't support templatizing many new services, and won't fully define even existing services that have since been updated. For example, Dynamo tables defined through CloudFormer won't contain TTL definitions or auto-scaling configuration. There is a third-party version of the tool with more supported resources called [Former2](https://github.com/iann0036/former2).\n-\t🔸Many users don’t use CloudFormation at all because of its limitations, or because they find other solutions preferable. Often there are other ways to accomplish the same goals, such as local scripts (Boto, Bash, Ansible, etc.) you manage yourself that build infrastructure, or Docker-based solutions ([Convox](https://convox.com/), etc.).\n-\t🔸Deploying large stacks (i.e., many resources) can be problematic due to unintuitive API limits. For instance, API Gateway's `CreateDeployment` API has a default limit of [3 requests per minute](https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html) as of 1/12/2018. This limit is readily exceeded even in moderately-sized CloudFormation stacks. Creating CW alarms is another commonly seen limit (`PutMetricAlarm`, 3 tps as of 1/12/2018) especially when creating many autoscaling policies for DynamoDB. One way to work around this limit is to include CloudFormation 'DependsOn' clauses to artificially chain resource creation.\n-\t🔸Creating/deleting stacks can be a little less clean than ideal. Some resources will leave behind traces in your AWS account even after deletion. E.g., Lambda will leave behind CloudWatch log groups that never expire.\n\nVPCs, Network Security, and Security Groups\n-------------------------------------------\n\n### VPC Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/vpc/) ∙ [User guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide) ∙ [FAQ](https://aws.amazon.com/vpc/faqs/) ∙ [Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) ∙ [Pricing](https://aws.amazon.com/vpc/pricing/)\n-\t**VPC** (Virtual Private Cloud) is the virtualized networking layer of your AWS systems.\n-\tMost AWS users should have a basic understanding of VPC concepts, but few need to get into all the details. VPC configurations can be trivial or extremely complex, depending on the extent of your network and security needs.\n-\tAll modern AWS accounts (those created [after 2013-12-04](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html)) are “EC2-VPC” accounts that support VPCs, and all instances will be in a default VPC. Older accounts may still be using “EC2-Classic” mode. Some features don’t work without VPCs, so you probably will want to [migrate](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html).\n\n[Back to top :arrow_up:](#table-of-contents)\n### VPC and Network Security Tips\n\n-\t❗**Security groups** are your first line of defense for your servers. Be extremely restrictive of what ports are open to all incoming connections. In general, if you use CLBs, ALBs or other load balancing, the only ports that need to be open to incoming traffic would be port 22 and whatever port your application uses. Security groups access policy is 'deny by default'.\n-\t**Port hygiene:** A good habit is to pick unique ports within an unusual range for each different kind of production service. For example, your web frontend might use 3010, your backend services 3020 and 3021, and your Postgres instances the usual 5432. Then make sure you have fine-grained security groups for each set of servers. This makes you disciplined about listing out your services, but also is more error-proof. For example, should you accidentally have an extra Apache server running on the default port 80 on a backend server, it will not be exposed.\n-\t**Migrating from Classic**: For migrating from older EC2-Classic deployments to modern EC2-VPC setup, [this article](https://blog.playfab.com/blog/how-playfab-migrated-ec2-classic-vpc-zero-downtime) may be of help.\n\t-\tYou can [migrate Elastic IPs between EC2-Classic and EC2-VPC](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html#using-eip-migration).\n-\tFor basic AWS use, one default VPC may be sufficient. But as you scale up, you should consider mapping out network topology more thoroughly. A good overview of best practices is [here](http://blog.flux7.com/blogs/aws/vpc-best-configuration-practices).\n-\tConsider controlling access to you private AWS resources through a [VPN](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpn-connections.html).\n\t-\tYou get better visibility into and control of connection and connection attempts.\n\t-\tYou expose a smaller surface area for attack compared to exposing separate (potentially authenticated) services over the public internet.\n\t\t-\te.g. A bug in the YAML parser used by the Ruby on Rails admin site is much less serious when the admin site is only visible to the private network and accessed through VPN.\n\t-\tAnother common pattern (especially as deployments get larger, security or regulatory requirements get more stringent, or team sizes increase) is to provide a [bastion host](https://www.pandastrike.com/posts/20141113-bastion-hosts) behind a VPN through which all SSH connections need to transit.\n\t-\tFor a cheap VPN to access private AWS resources, consider using a point-to-site software VPN such as [OpenVPN](https://openvpn.net/). It can either be installed using the [official AMI](https://docs.openvpn.net/how-to-tutorialsguides/virtual-platforms/amazon-ec2-appliance-ami-quick-start-guide/), though you are limited to 2 concurrent users on the free license, or it can be installed using the openvpn package on linux. The linux package allows for unlimited concurrent users but the installation is less straightforward. This [OpenVPN installer script](https://github.com/Nyr/openvpn-install) can help you install it and add client keys easily.\n-\t🔹Consider using other security groups as sources for security group rules instead of using CIDRs — that way, all hosts in the source security group and only hosts in that security group are allowed access. This is a much more dynamic and secure way of managing security group rules.\n-\t**VPC Flow Logs** allow you to monitor the network traffic to, from, and within your VPC. Logs are stored in CloudWatch Logs groups, and can be used for security monitoring (with third party tools), performance evaluation, and forensic investigation.\n\t-\tSee the [VPC Flow Logs User Guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/flow-logs.html) for basic information.\n\t-\tSee the [flowlogs-reader](https://github.com/obsrvbl/flowlogs-reader) CLI tool and Python library to retrieve and work with VPC Flow Logs.\n- **IPv6** [is available in VPC](https://aws.amazon.com/blogs/aws/new-ipv6-support-for-ec2-instances-in-virtual-private-clouds/). Along with this announcement came the introduction of the [Egress-Only Internet Gateway](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/egress-only-internet-gateway.html). In cases where one would use NAT Gateways to enable egress-only traffic for their VPC in IPv4, one can use an Egress-Only Internet Gateway for the same purpose in IPv6.\n\n-\tAmazon provides an IPv6 CIDR block for your VPC at your request - at present you cannot implement your own IPv6 block if you happen to own one already.\n-\tNew and existing VPCs can both use IPv6. Existing VPCs will need to be configured to have an IPv6 CIDR block associated with them, just as new VPCs do.\n\n[Back to top :arrow_up:](#table-of-contents)\n### PrivateLink\n- 📒[Homepage](https://aws.amazon.com/privatelink/) ∙ [User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/vpce-interface.html) ∙  [Pricing](https://aws.amazon.com/privatelink/pricing/)\n- One of the uses for Private link is [Interface VPC Endpoints](https://docs.aws.amazon.com/vpc/latest/userguide/vpce-interface.html) deploys an ENI into your VPC and subnets which allows you direct access to the AWS API's as if the were accessible locally in your VPC without having to go out to the internet.\n- Another use case would be to expose a service of your own to other accounts in AWS through a [VPC Endpoint Service](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-service.html)\n\n[Back to top :arrow_up:](#table-of-contents)\n### VPC and Network Security Gotchas and Limitations\n-\t🔸VPCs are tied to one Region in one Account. Subnets are tied to one VPC and limited to one Availability Zone.\n-\t🔸Security groups are tied to one VPC. If you are utilizing infrastructure in multiple VPCs you should make sure your configuration/deployment tools take that into account.\n-\t🔸[VPC Endpoints](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-endpoints.html) are currently only available for S3 and DynamoDB. If you have a security requirement to lockdown outbound traffic from your VPC you may want to use [DNS filtering](https://aws.amazon.com/blogs/security/how-to-add-dns-filtering-to-your-nat-instance-with-squid/) to control outbound traffic to other services.\n-\t❗Be careful when choosing your VPC IP CIDR block: If you are going to need to make use of [ClassicLink](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html), make sure that your private IP range [doesn’t overlap](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html#classiclink-limitations) with that of EC2 Classic.\n-\t❗If you are going to peer VPCs, carefully consider the cost of [data transfer between VPCs](https://aws.amazon.com/vpc/faqs/#Peering_Connections), since for some workloads and integrations, this can be prohibitively expensive.\n- ❗New RDS instances require a [subnet group](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.WorkingWithRDSInstanceinaVPC.html#USER_VPC.Subnets) within your VPC. If you’re using the [default VPC](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/default-vpc.html) this isn’t a concern, it will contain a subnet for each availability zone in your region. However, if you’re creating your own VPC and plan on using RDS, make sure you have at least two subnets within the VPC to act as the subnet group.\n-\t❗If you delete the default VPC, you can [recreate it via the CLI or the console](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/default-vpc.html#create-default-vpc).\n-\t❗Be careful with VPC VPN credentials! If lost or compromised, the VPN endpoint must be deleted and recreated. See the instructions for [Replacing Compromised Credentials](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_VPN.html#CompromisedCredentials).\n-\t❗Security Groups and Route Tables apply entries separately for IPv4 and IPv6, so one must ensure they add entries for both protocols accordingly.\n- \t💸Managed NAT gateways are a convenient alternative to\nmanually managing [NAT instances](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPCNATInstance.html), but they do come at a cost per gigabyte. Consider [alternatives](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-comparison.html) if you're transferring many terabytes from private subnets to the internet. If you transfer terabytes/petabytes of data from EC2 instances in private subnets to S3, avoid the [NAT gateway data processing charge](https://aws.amazon.com/vpc/pricing/) by setting up a Gateway Type VPC Endpoint and route the traffic to/from S3 through the VPC endpoints instead of going through the NAT gateways.\n\nKMS\n---\n\n### KMS Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/kms/) ∙ [Developer guide](http://docs.aws.amazon.com/kms/latest/developerguide/) ∙ [FAQ](https://aws.amazon.com/kms/faqs/) ∙ [Pricing](https://aws.amazon.com/kms/pricing/)\n-\t**KMS** (Key Management Service) is a secure service for creating, storing and auditing usage of cryptographic keys.\n- **Service integration:** KMS [integrates with other AWS services](http://docs.aws.amazon.com/kms/latest/developerguide/service-integration.html): EBS, Elastic Transcoder, EMR, Redshift, RDS, SES, S3, WorkMail and Workspaces.\n- **Encryption APIs:** The [Encrypt](http://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) and [Decrypt API](http://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) allow you to encrypt and decrypt data on the KMS service side, never exposing the master key contents.\n- **Data keys:** The [GenerateDataKey](http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys) API generates a new key off of a master key. The data key contents are exposed to you so you can use it to encrypt and decrypt any size of data in your application layer. KMS does not store, manage or track data keys, you are responsible for this in your application.\n- 🔹**Auditing:** Turn on CloudTrail to audit all KMS API events.\n- **Access:** Use [key policies](http://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html) and [IAM policies](http://docs.aws.amazon.com/kms/latest/developerguide/iam-policies.html) to grant different levels of KMS access. For example, you create an IAM policy that only [allows a user to encrypt and decrypt with a specific key](http://docs.aws.amazon.com/kms/latest/developerguide/iam-policies.html#iam-policy-example-encrypt-decrypt-specific-cmks).\n\n[Back to top :arrow_up:](#table-of-contents)\n### KMS Tips\n\n-\t🔹It’s very common for companies to manage keys completely via home-grown mechanisms, but it’s far preferable to use a service such as KMS from the beginning, as it encourages more secure design and improves policies and processes around managing keys.\n-\tA good motivation and overview is in [this AWS presentation](http://www.slideshare.net/AmazonWebServices/encryption-and-key-management-in-aws).\n-\tThe cryptographic details are in [this AWS whitepaper](https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf).\n-\t[This blog from Convox](https://convox.com/blog/encryption-at-rest) demonstrates why and how to use KMS for encryption at rest.\n\n[Back to top :arrow_up:](#table-of-contents)\n### KMS Gotchas and Limitations\n\n-\t🔸The Encrypt API only works with < 4KB of data. Larger data requires generating and managing a [data key](http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys) in your application layer.\n-\t🔸KMS audit events are not available in the [CloudTrail Lookup Events API](http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_LookupEvents.html). You need to look find them in the raw .json.gz files that CloudTrail saves in S3.\n-\t🔸In order to encrypt a multi-part upload to S3, the KMS Key Policy needs to allow “kms:Decrypt” and “kms:GenerateDataKey*” in addition to “kms:Encrypt”, otherwise the upload will fail with an “AccessDenied” error.\n-\t🔸KMS keys are region specific — they are stored and can only be used in the region in which they are created. They can't be transferred to other regions.\n-\t🔸KMS keys have a key policy that must grant access to something to manage the key.  If you don't grant anything access to the key on creation, then you have to reach out to support to have the key policy reset [Reduce the Risk of the Key Becoming Unmanagable](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html#key-policy-default-allow-root-enable-iam).\n-\t🔸If you use a key policy to grant access to IAM roles or users and then delete the user/role, recreating the user or role won't grant them permission to the key again.\n\n\nCloudFront\n----------\n\n### CloudFront Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/cloudfront/) ∙ [Developer guide](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/) ∙ [FAQ](https://aws.amazon.com/cloudfront/faqs/) ∙ [Pricing](https://aws.amazon.com/cloudfront/pricing/)\n-\t**CloudFront** is AWS’ [content delivery network (CDN)](https://en.wikipedia.org/wiki/Content_delivery_network).\n-\tIts primary use is improving latency for end users through accessing cacheable content by hosting it at [over 60 global edge locations](http://aws.amazon.com/cloudfront/details/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### CloudFront Alternatives and Lock-in\n\n-\t🚪CDNs are [a highly fragmented market](https://www.datanyze.com/market-share/cdn/). CloudFront has grown to be a leader, but there are many alternatives that might better suit specific needs.\n\n[Back to top :arrow_up:](#table-of-contents)\n### CloudFront Tips\n\n-\t🐥**IPv6** is [supported](https://aws.amazon.com/about-aws/whats-new/2016/10/ipv6-support-for-cloudfront-waf-and-s3-transfer-acceleration/). This is a configurable setting, and is enabled by default on new CloudFront distributions. IPv6 support extends to the use of WAF with CloudFront.\n-\t🐥**HTTP/2** is [now supported](https://aws.amazon.com/about-aws/whats-new/2016/09/amazon-cloudfront-now-supports-http2/)! Clients [must support TLS 1.2 and SNI](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesSupportedHTTPVersions).\n-\tWhile the most common use is for users to browse and download content (GET or HEAD methods) requests, CloudFront also supports ([since 2013](https://aws.amazon.com/blogs/aws/amazon-cloudfront-content-uploads-post-put-other-methods/)) uploaded data (POST, PUT, DELETE, OPTIONS, and PATCH).\n\t-\tYou must enable this by specifying the [allowed HTTP methods](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesAllowedHTTPMethods) when you create the distribution.\n\t-\tInterestingly, the cost of accepting (uploaded) data [is usually less](https://aws.amazon.com/cloudfront/pricing/) than for sending (downloaded) data.\n-\tIn its basic version, CloudFront [supports SSL](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html) via the [SNI extension to TLS](https://en.wikipedia.org/wiki/Server_Name_Indication), which is supported by all modern web browsers. If you need to support older browsers, you need to pay a few hundred dollars a month for dedicated IPs.\n\t-\t💸⏱Consider invalidation needs carefully. CloudFront [does support invalidation](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html) of objects from edge locations, but this typically takes many minutes to propagate to edge locations, and costs $0.005 per request after the first 1000 requests. (Some other CDNs support this better.)\n-\tEveryone should use TLS nowadays if possible. [Ilya Grigorik’s table](https://istlsfastyet.com/#cdn-paas) offers a good summary of features regarding TLS performance features of CloudFront.\n-\tAn alternative to invalidation that is often easier to manage, and instant, is to configure the distribution to [cache with query strings](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/QueryStringParameters.html) and then append unique query strings with versions onto assets that are updated frequently.\n-\t⏱For good web performance, it is recommended to [enable compression](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html) on CloudFront distributions if the origin is S3 or another source that does not already compress.\n\n[Back to top :arrow_up:](#table-of-contents)\n### CloudFront Gotchas and Limitations\n\n-\t🔸If using S3 as a backing store, remember that the endpoints for website hosting and for general S3 are different. Example: “bucketname.s3.amazonaws.com” is a standard S3 serving endpoint, but to have redirect and error page support, you need to use the website hosting endpoint listed for that bucket, e.g. “bucketname.s3-website-us-east-1.amazonaws.com” (or the appropriate region).\n-\t🔸By default, CloudFront will not forward HTTP Host: headers through to your origin servers. This can be problematic for your origin if you run multiple sites switched with host headers. You can [enable host header forwarding](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#request-custom-headers-behavior) in the default cache behavior settings.\n-\t🔸4096-bit SSL certificates: CloudFront do not support 4096-bit SSL certificates as of late 2016. If you are using an externally issued SSL certificate, you’ll need to make sure it’s 2048 bits. See [ongoing discussion](https://forums.aws.amazon.com/thread.jspa?threadID=148783).\n- Although connections from clients to CloudFront edge servers can make use of IPv6, [connections to the origin server will continue to use IPv4.](https://aws.amazon.com/about-aws/whats-new/2016/10/ipv6-support-for-cloudfront-waf-and-s3-transfer-acceleration/)\n\nDirectConnect\n-------------\n\n### DirectConnect Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/directconnect/) ∙ [User guide](http://docs.aws.amazon.com/directconnect/latest/UserGuide/) ∙ [FAQ](https://aws.amazon.com/directconnect/faqs/) ∙ [Pricing](https://aws.amazon.com/directconnect/pricing/)\n-\t**Direct Connect** is a private, dedicated connection from your network(s) to AWS.\n\n[Back to top :arrow_up:](#table-of-contents)\n### DirectConnect Tips\n\n-\tIf your data center has [a partnering relationship](https://aws.amazon.com/directconnect/partners/) with AWS, setup is streamlined.\n-\tUse for more consistent predictable network performance guarantees (**1 Gbps** or **10 Gbps** per link).\n-\tUse to peer your colocation, corporate, or physical datacenter network with your VPC(s).\n\t-\tExample: Extend corporate LDAP and/or Kerberos to EC2 instances running in a VPC.\n\t-\tExample: Make services that are hosted outside of AWS for financial, regulatory, or legacy reasons callable from within a VPC.\n\nRedshift\n--------\n\n### Redshift Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/redshift/) ∙ [Developer guide](http://docs.aws.amazon.com/redshift/latest/dg/) ∙ [FAQ](https://aws.amazon.com/redshift/faqs/) ∙ [Pricing](https://aws.amazon.com/redshift/pricing/)\n-\t**Redshift** is AWS’ managed [data warehouse](https://en.wikipedia.org/wiki/Data_warehouse) solution, which is massively parallel, scalable, and columnar. It is very widely used. It [was built](https://en.wikipedia.org/wiki/Amazon_Redshift) using [ParAccel](https://en.wikipedia.org/wiki/ParAccel) technology and exposes [Postgres](https://en.wikipedia.org/wiki/PostgreSQL)-compatible interfaces.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Redshift Alternatives and Lock-in\n\n-\t⛓🚪Whatever data warehouse you select, your business will likely be locked in for a long time. Also (and not coincidentally) the data warehouse market is highly fragmented. Selecting a data warehouse is a choice to be made carefully, with research and awareness of [the market landscape](https://www.datanami.com/2016/03/14/data-warehouse-market-ripe-disruption-gartner-says/) and what [business intelligence](https://en.wikipedia.org/wiki/Business_intelligence) tools you’ll be using.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Redshift Tips\n\n-\tAlthough Redshift is mostly Postgres-compatible, its SQL dialect and performance profile are different.\n-\tRedshift supports only [12 primitive data types](https://docs.aws.amazon.com/redshift/latest/dg/c_Supported_data_types.html). ([List of unsupported Postgres types](https://docs.aws.amazon.com/redshift/latest/dg/c_unsupported-postgresql-datatypes.html)\\)\n-\tIt has a leader node and computation nodes (the leader node distributes queries to the computation ones). Note that some functions [can be executed only on the lead node.](https://docs.aws.amazon.com/redshift/latest/dg/c_SQL_functions_leader_node_only.html)\n-\t🔹Make sure to create a new [cluster parameter group](http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html) and option group for your database since the default parameter group does not allow dynamic configuration changes.\n-\tMajor third-party BI tools support Redshift integration (see [Quora](https://www.quora.com/Which-BI-visualisation-solution-goes-best-with-Redshift)).\n-\t[Top 10 Performance Tuning Techniques for Amazon Redshift](https://blogs.aws.amazon.com/bigdata/post/Tx31034QG0G3ED1/Top-10-Performance-Tuning-Techniques-for-Amazon-Redshift) provides an excellent list of performance tuning techniques.\n-\t[Amazon Redshift Utils](https://github.com/awslabs/amazon-redshift-utils) contains useful utilities, scripts and views to simplify Redshift ops.\n-\t[VACUUM](http://docs.aws.amazon.com/redshift/latest/dg/t_Reclaiming_storage_space202.html) regularly following a significant number of deletes or updates to reclaim space and improve query performance.\n-\tAvoid performing blanket [VACUUM](http://docs.aws.amazon.com/redshift/latest/dg/r_VACUUM_command.html) or [ANALYZE](http://docs.aws.amazon.com/redshift/latest/dg/r_ANALYZE.html) operations at a cluster level. The checks on each table to determine whether VACUUM or ANALYZE action needs to be taken is wasteful. Only perform ANALYZE and VACUUM commands on the objects that require it. Utilize the [Analyze & Vacuum Schema Utility](https://github.com/awslabs/amazon-redshift-utils/tree/master/src/AnalyzeVacuumUtility) to perform this work. The SQL to determine whether a table needs to be VACUUMed or ANALYZEd can be found in the [Schema Utility README](https://github.com/awslabs/amazon-redshift-utils/blob/master/src/AnalyzeVacuumUtility/README.md) if you wish to create your own maintenance process.\n-\tRedshift provides various [column compression](http://docs.aws.amazon.com/redshift/latest/dg/t_Compressing_data_on_disk.html) options to optimize the stored data size. AWS strongly encourages users to use [automatic compression](http://docs.aws.amazon.com/redshift/latest/dg/c_Loading_tables_auto_compress.html) at the [COPY](https://docs.aws.amazon.com/redshift/latest/dg/r_COPY.html) stage, when Redshift uses a sample of the data being ingested to analyze the column compression options. However, automatic compression can only be applied to an empty table with no data. Therefore, make sure the initial load batch is big enough to provide Redshift with a representative sample of the data (the default sample size is 100,000 rows).\n-\tRedshift uses columnar storage, hence it does not have indexing capabilities. You can, however, use [distribution key](http://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-best-dist-key.html) and [sortkey](http://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-sort-key.html) to improve performance. Redshift has two types of sort keys: compounding sort key and interleaved sort key.\n-\tA compound sort key is made up of all columns listed in the sort key definition. It is most useful when you have queries with operations using the prefix of the sortkey.\n-\tAn interleaved sort key on the other hand gives equal weight to each column or a subset of columns in the sort key. So if you don't know ahead of time which column(s) you want to choose for sorting and filtering, this is a much better choice than the compound key. [Here](https://aws.amazon.com/blogs/aws/quickly-filter-data-in-amazon-redshift-using-interleaved-sorting/) is an example using interleaved sort key.\n-\t🔸⏱ **Distribution strategies:** Since data in Redshift is physically distributed among nodes, choosing the right data **distribution key** and [distribution style](http://docs.aws.amazon.com/redshift/latest/dg/c_choosing_dist_sort.html) is crucial for adequate query performance. There are three possible distribution style settings — **EVEN** (the default), **KEY**, or **ALL**. Use KEY to collocate join key columns for tables which are joined in queries. Use ALL to place the data in small-sized tables on all cluster nodes.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Redshift Gotchas and Limitations\n\n-\t❗⏱While Redshift can handle heavy queries well, it does not scale horizontally, i.e. does not handle multiple queries in parallel. Therefore, if you expect a high parallel load, consider replicating or (if possible) sharding your data across multiple clusters.\n-\t🔸 The leader node, which manages communications with client programs and all communication with compute nodes, is the single point of failure.\n-\t⏱Although most Redshift queries parallelize well at the compute node level, certain stages are executed on the leader node, which can become the bottleneck.\n-\t🔹Redshift data commit transactions are very expensive and serialized at the cluster level. Therefore, consider grouping multiple mutation commands (COPY/INSERT/UPDATE) commands into a single transaction whenever possible.\n-\t🔹Redshift does not support multi-AZ deployments. Building multi-AZ clusters is not trivial. [Here](https://blogs.aws.amazon.com/bigdata/post/Tx13ZDHZANSX9UX/Building-Multi-AZ-or-Multi-Region-Amazon-Redshift-Clusters) is an example using Kinesis.\n-\t🔸Beware of storing multiple small tables in Redshift. The way Redshift tables are laid out on disk makes it impractical. The minimum space required to store a table (in MB) is nodes * slices/node * columns. For example, on a 16 node cluster an empty table with 20 columns will occupy 640MB on disk.\n-\t⏱ Query performance degrades significantly during data ingestion. [WLM (Workload Management)](http://docs.aws.amazon.com/redshift/latest/dg/c_workload_mngmt_classification.html) tweaks help to some extent. However, if you need consistent read performance, consider having replica clusters (at the extra cost) and swap them during update.\n-\t❗ Never resize a live cluster. The resize operation can take hours depending on the dataset size. In rare cases, the operation may also get stuck and you'll end up having a non-functional cluster. The safer approach is to create a new cluster from a snapshot, resize the new cluster and shut down the old one.\n-\t🔸Redshift has **reserved keywords** that are not present in Postgres (see full list [here](https://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html)). Watch out for DELTA ([Delta Encodings](https://docs.aws.amazon.com/redshift/latest/dg/c_Delta_encoding.html)).\n-\t🔸Redshift does not support many Postgres functions, most notably several date/time-related and aggregation functions. See the [full list here](https://docs.aws.amazon.com/redshift/latest/dg/c_unsupported-postgresql-functions.html).\n-\t🔸 Uniqueness, primary key, and foreign key constraints on Redshift tables are informational only and are not enforced. They are, however, used by the query optimizer to generate query plans. `NOT NULL` column constraints are enforced. See [here](https://docs.aws.amazon.com/redshift/latest/dg/t_Defining_constraints.html) for more information on defining constraints.\n-\t🔸Compression on sort key [can result in significant performance impact](https://aws.amazon.com/blogs/big-data/optimizing-for-star-schemas-and-interleaved-sorting-on-amazon-redshift/). So if your Redshift queries involving sort key(s) are slow, you might want to consider removing compression on a sort key.\n-\t🔹 [Choosing a sort key](http://docs.aws.amazon.com/redshift/latest/dg/t_Sorting_data.html) is very important since you can not change a table’s sort key after it is created. If you need to change the sort or distribution key of a table, you need to create a new table with the new key and move your data into it with a query like “insert into new_table select * from old_table”.\n-\t❗🚪 When moving data with a query that looks like “insert into x select from y”, you need to have twice as much disk space available as table “y” takes up on the cluster’s disks. Redshift first copies the data to disk and then to the new table. [Here](https://www.periscopedata.com/blog/changing-dist-and-sort-keys-in-redshift.html) is a good article on how to this for big tables.\n\nEMR\n---\n\n### EMR Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/emr/) ∙ [Release guide](http://docs.aws.amazon.com/ElasticMapReduce/latest/ReleaseGuide/) ∙ [FAQ](https://aws.amazon.com/emr/faqs/) ∙ [Pricing](https://aws.amazon.com/emr/pricing/)\n-\t**EMR** (which used to stand for Elastic Map Reduce, but not anymore, since it now extends beyond map-reduce) is a service that offers managed deployment of [Hadoop](https://en.wikipedia.org/wiki/Apache_Hadoop), [HBase](https://en.wikipedia.org/wiki/Apache_HBase) and [Spark](https://en.wikipedia.org/wiki/Apache_Spark). It reduces the management burden of setting up and maintaining these services yourself.\n\n[Back to top :arrow_up:](#table-of-contents)\n### EMR Alternatives and Lock-in\n\n-\t⛓Most of EMR is based on open source technology that you can in principle deploy yourself. However, the job workflows and much other tooling is AWS-specific. Migrating from EMR to your own clusters is possible but not always trivial.\n\n[Back to top :arrow_up:](#table-of-contents)\n### EMR Tips\n\n-\tEMR relies on many versions of Hadoop and other supporting software. Be sure to check [which versions are in use](https://docs.aws.amazon.com/ElasticMapReduce/latest/ReleaseGuide/emr-release-components.html).\n-\t⏱Off-the-shelf EMR and Hadoop can have significant overhead when compared with efficient processing on a single machine. If your data is small and performance matters, you may wish to consider alternatives, as [this post](https://adamdrake.com/command-line-tools-can-be-235x-faster-than-your-hadoop-cluster.html) illustrates.\n-\tPython programmers may want to take a look at Yelp’s [mrjob](https://github.com/Yelp/mrjob).\n-\tIt takes time to tune performance of EMR jobs, which is why third-party services such as [Qubole’s data service](https://www.qubole.com/mapreduce-as-a-service/) are gaining popularity as ways to improve performance or reduce costs.\n\n[Back to top :arrow_up:](#table-of-contents)\n### EMR Gotchas and Limitations\n\n-\t💸❗**EMR costs** can pile up quickly since it involves lots of instances, efficiency can be poor depending on cluster configuration and choice of workload, and accidents like hung jobs are costly. See the [section on EC2 cost management](#ec2-cost-management), especially the tips there about Spot instances. [This blog post](https://aws.amazon.com/blogs/big-data/strategies-for-reducing-your-amazon-emr-costs/) has additional tips, but was written prior to the shift to per-second billing.\n-\t💸 Beware of “double-dipping”. With EMR, you pay for the EC2 capacity and the service fees. In addition, EMR syncs task logs to S3, which means you pay for the storage and **PUT requests** at [S3 standard rates](https://aws.amazon.com/s3/pricing/#Request_Pricing). While the log files tend to be relatively small, every Hadoop job, depending on the size, generates thousands of log files that can quickly add up to thousands of dollars on the AWS bill. YARN’s [log aggregation](http://hortonworks.com/blog/simplifying-user-logs-management-and-access-in-yarn/) is not available on EMR.\n\nKinesis Streams\n---\n\n### Kinesis Streams Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/kinesis/streams/) ∙ [Developer guide](https://docs.aws.amazon.com/streams/latest/dev/introduction.html) ∙ [FAQ](https://aws.amazon.com/kinesis/streams/faqs/) ∙ [Pricing](https://aws.amazon.com/kinesis/streams/pricing/)\n-\t**Kinesis Streams** (which used to be only called Kinesis, before Kinesis Firehose and Kinesis Analytics were launched) is a service that allows you to ingest high-throughput data streams for immediate or delayed processing by other AWS services.\n- Kinesis Streams’ subcomponents are called [**shards**](https://docs.aws.amazon.com/streams/latest/dev/key-concepts.html). Each shard provides 1MB/s of write capacity and 2MB/s of read capacity at a maximum of 5 reads per second. A stream can have its shards programmatically increased or decreased based on a variety of metrics.\n- All records entered into a Kinesis Stream are assigned a unique sequence number as they are captured. The records in a Stream are ordered by this number, so any time-ordering is preserved.\n- [This page](http://docs.aws.amazon.com/streams/latest/dev/key-concepts.html) summarizes key terms and concepts for Kinesis Streams.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Kinesis Streams Alternatives and Lock-in\n\n-\t🚪 Kinesis is most closely compared to [Apache Kafka](https://kafka.apache.org/), an open-source data ingestion solution. It is possible to set up a Kafka cluster hosted on [EC2 instances](#ec2) (or any other VPS), however you are responsible for managing and maintaining both Zookeeper and the Kafka brokers in a highly available configuration. Confluent has a good blog post with their recommendations on how to do this [here](http://www.confluent.io/blog/design-and-deployment-considerations-for-deploying-apache-kafka-on-aws/), which has links on the bottom to several other blogs they have written on the subject.\n-\t⛓ Kinesis uses very AWS-specific APIs, so you should be aware of the potential future costs of migrating away from it, should you choose to use it.\n-\tAn application that efficiently uses Kinesis Streams will scale the number of shards up and down based on the required streaming capacity. (Note there is no direct equivalent to this with Apache Kafka.)\n\n\n[Back to top :arrow_up:](#table-of-contents)\n### Kinesis Streams Tips\n\n-\tThe [KCL](https://docs.aws.amazon.com/streams/latest/dev/developing-consumers-with-kcl.html) (Kinesis Client Library) provides a skeleton interface for Java, Node, Python, Ruby and .NET programs to easily consume data from a Kinesis Stream. In order to start consuming data from a Stream, you only need to provide a config file to point at the correct Kinesis Stream, and functions for initialising the consumer, processing the records, and shutting down the consumer within the skeletons provided.\n\t- The KCL uses a DynamoDB table to keep track of which records have been processed by the KCL. This ensures that all records are processed “at least once”. It is up to the developer to ensure that the program can handle doubly-processed records.\n\t- The KCL also uses DynamoDB to keep track of other KCL “workers”. It automatically shares the available Kinesis Shards across all the workers as equally as possible.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Kinesis Streams Gotchas and Limitations\n\n- 🔸⏱  Kinesis Streams’ shards each only permit [5 reads per second](http://docs.aws.amazon.com/streams/latest/dev/service-sizes-and-limits.html). If you are evenly distributing data across many shards, your read limit for the Stream will remain at 5 reads per second on aggregate, as each consuming application will need to check every single shard for new records. This puts a hard limit on the number of different consuming applications possible per Stream for a given maximum read latency.\n   - For example, if you have 5 consuming applications reading data from one Stream with any number of shards, they cannot read with a latency of less than one second, as each of the 5 consumers will need to poll *each shard* every second, reaching the cap of 5 reads per second per shard.\n\t- [This blog post](https://brandur.org/kinesis-in-production) further discusses the performance and limitations of Kinesis in production.\n-\t💸 **Kinesis Streams are not included in the free tier.** Make sure if you do any experimentation with it on a personal account, you shut down the stream or it may run up unexpected costs (~$11 per shard-month.)\n\nKinesis Firehose\n---\n\n[Back to top :arrow_up:](#table-of-contents)\n### Kinesis Firehose Gotchas and Limitations\n\n- 🔸 📜 When delivering from Firehose to Elasticsearch, the JSON document cannot contain an “_id” property. Firehose will not attempt to deliver those documents and won't log any error.\n\n\nDevice Farm\n-----------\n\n### Device Farm Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/device-farm/) ∙ [Developer guide](http://docs.aws.amazon.com/devicefarm/latest/developerguide/) ∙ [FAQ](https://aws.amazon.com/device-farm/faq/) ∙ [Pricing](https://aws.amazon.com/device-farm/pricing/)\n- **Device Farm** is an AWS service that enables mobile app testing on real devices.\n- Supports iOS and Android (including Kindle Fire) devices, as well as the mobile web.\n- Supports remote device access in order to allow for interactive testing/debugging.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Device Farm Tips\n\n- [AWS Mobile blog](https://aws.amazon.com/blogs/mobile/) contains several examples of Device Farm usage for testing.\n- Device Farm offers a free trial for users who want to evaluate their service.\n- Device Farm offers two pricing models: Paying **per device minute** is useful for small usage levels or for situations where it‘s hard to predict usage amount. **Unmetered plans** are useful in situations where active usage is expected from the beginning.\n- To minimize waiting time for device availability, one approach is to create several device pools with different devices, then randomly choose one of the unused device pools on every run.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Device Farm Gotchas and Limitations\n\n- ❗Devices don't have a SIM card and therefore can‘t be used for testing SIM card-related features.\n- 🔸Device Farm supports testing for most popular languages/frameworks, but not for all. An actual list of supported frameworks and languages is presented on [this page](http://docs.aws.amazon.com/devicefarm/latest/developerguide/test-types-overview.html).\n- 🔸The API and CLI for Device Farm is quite a low level and may require developing additional tools or scripts on top of it.\n- 🔸AWS provide several tools and plugins for Device Farm, however, it doesn‘t cover all cases or platforms. It may require developing specific tools or plugins to support specific requirements.\n- ❗In general, Device Farm doesn‘t have Android devices from Chinese companies like Huawei, Meizu, Lenovo, etc. An actual list of supported devices located [here](https://aws.amazon.com/device-farm/device-list/).\n- 🔸Device availability is uneven. It depends on several factors including device popularity. Usually, more modern devices see higher demand, thus the waiting time for them will be higher compared to relatively old devices.\n\nMobile Hub\n----------\n\n### Mobile Hub Basics\n\n* 📒 [Homepage](https://aws.amazon.com/mobile/) ∙ [User guide](https://docs.aws.amazon.com/aws-mobile/latest/developerguide/what-is-aws-mobile.html) ∙ [FAQ](https://aws.amazon.com/mobile/faqs/) ∙ [Pricing](https://aws.amazon.com/mobile/pricing/)\n- **Mobile Hub** orchestrates multiple services to create an AWS backend for mobile and web applications.\n- Each _project_ in Mobile Hub has one _backend_ made up of configurable features, plus one or more _applications_.\n - Features include Analytics, Cloud Logic, Conversational Bots, Hosting and Streaming, NoSQL Database, User Data Storage and User Sign-In. Each feature uses one or two services to deliver a chunk of functionality.\n - Services used include [API Gateway](#api-gateway), [CloudFront](#cloudfront), Cognito, [Device Farm](#device-farm), [DynamoDB](#dynamodb), [Lambda](#lambda), Lex, Pinpoint and [S3](#S3).\n - Application SDKs exist for Android (Java), iOS (Swift), Web (JS) and React Native (JS). There is also a CLI for JavaScript applications.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Mobile Hub Tips\n- The Mobile Hub [console](https://console.aws.amazon.com/mobilehub/home#/) has starter kits and tutorials for various app platforms.\n- The CLI allows local development of Lambda code (JS by default) with `awsmobile {pull|push}` commands, to sync from cloud to folder, and back again.\n- Mobile Hub itself is free, but each of the services has its own pricing model.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Mobile Hub Gotchas and Limitations\n- 🔸The Cloud API feature allows importing an existing Lambda function instead of defining a new one, but there are some rough edges with the CLI. Check the GitHub [issues](https://github.com/aws/awsmobile-cli/issues).\n- ❗Mobile Hub uses CloudFormation under the covers, and gets confused when a service is changed outside of the Mobile Hub console.\n\nIoT\n---\n\n### IoT Basics\n\n* \t📒 [Homepage](https://aws.amazon.com/iot/) ∙ [User guide](https://docs.aws.amazon.com/iot/latest/developerguide/) ∙ [FAQ](https://aws.amazon.com/iot/faqs/) ∙ [Pricing](https://aws.amazon.com/iot/pricing/)\n- \t**IoT** is a platform for allowing clients such as IoT devices or software applications ([examples](http://internetofthingswiki.com/iot-applications-examples/541/)) to communicate with the AWS cloud.\n- \tClients are also called **devices** (or **things**) and include a wide variety of device types.  Roughly there are three categories of device types that interact with IoT services by sending message over an IoT protocol to the IoT Pub/Sub-style message broker, which is called the IoT **Device Gateway**:\n    * \tSend messages only: For example, the [AWS IoT Button](https://aws.amazon.com/iot/button/) on an [eddystone beacon](http://developer.estimote.com/eddystone/).\n    * \tSend, receive, and process messages: For example, a simple processing board, such as a **Raspberry Pi** ([quick start guide](http://docs.aws.amazon.com/iot/latest/developerguide/iot-device-sdk-c.html)), or an Alexa device, such as the [Echo or Echo Dot](https://amazon.com/echo). These are designed to work with the [Alexa skills kit](https://developer.amazon.com/alexa-skills-kit), a programmable voice-enabled service.\n- \tAWS has a useful [quick-start](http://docs.aws.amazon.com/iot/latest/developerguide/iot-gs.html) (using the Console) and a [slide presentation](http://www.slideshare.net/AmazonWebServices/connecting-to-aws-iot) on core topics.\n* **IoT terms:**\n    * \tAWS [**IoT Things**](http://docs.aws.amazon.com/iot/latest/developerguide/iot-thing-management.html) (metadata for devices in a [registry](http://docs.aws.amazon.com/iot/latest/developerguide/iot-thing-management.html)) and can store device state in a JSON document, which is called a [**device shadow**](http://docs.aws.amazon.com/iot/latest/developerguide/iot-thing-shadows.html).  Device metadata can also be stored in [**IoT Thing Types**](http://docs.aws.amazon.com/iot/latest/developerguide/thing-types.html). This aids in device metadata management by allowing for reuse of device description and configuration for more than one device.  Note that IoT Thing Types can be deprecated, but not changed — they are immutable.\n    * \tAWS [**IoT Certificates**](http://docs.aws.amazon.com/iot/latest/developerguide/attach-cert-thing.html) (device authentication) are the logical association of a unique certificate to the logical representation of a device. This association can be done in the Console.  In addition, the public key of the certificate must be copied to the physical device. This covers the authentication of devices to a particular AWS Device Gateway (or message broker). You can associate an AWS IoT certificate with an IoT device or you can [register your own CA (Certificate Authority) with AWS](http://docs.aws.amazon.com/iot/latest/developerguide/device-certs-your-own.html), generate your own certificate(s) and associate those certificates with your devices via the AWS Console or cli.\n    * \tAWS [**IoT Policies**](http://docs.aws.amazon.com/iot/latest/developerguide/authorization.html) (device/topic authorization) are JSON files that are associated to one or more AWS IoT certificates. This authorizes associated devices to publish and/or subscribe to messages from one or more MQTT topics.\n    * \tAWS [**IoT Rules**](http://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) are SQL-like queries which allows for reuse of some or all device message data, as described in [this presentation, which summarizes design patterns with for IoT Rules](http://www.slideshare.net/AmazonWebServices/programming-the-physical-world-with-device-shadows-and-rules-engine-66486454).\n    * \tShown below is a [diagram](https://aws.amazon.com/iot/how-it-works/) which summarizes the flow of messages between the AWS IoT services:\n\n![How AWS IoT Works](https://d0.awsstatic.com/IoT/diagrams/awsiot-how-it-works_HowITWorks_1-26.png \"How AWS IoT Works\")\n\n[Back to top :arrow_up:](#table-of-contents)\n### IoT Greengrass\n\n* 📒 [Homepage](https://aws.amazon.com/greengrass/)\n* 🐥**Greengrass** is a software platform that extends AWS IoT capabilities allowing Lambda functions to be run directly on local devices.  It also enables IoT devices to be able to securely communicate on a local network without having to connect to the cloud.\n    * Greengrass includes a local pub/sub message manager that can buffer messages if connectivity is lost so that inbound and outbound messages to the cloud are preserved. Locally deployed Lambda functions can be triggered by local events, messages from the cloud, or other sources.\n    * Greengrass includes secure authentication and authorization of devices within the local network and also between the local network and the AWS cloud. It also provides secure, over-the-air software updates of Lambda functions.\n*  Greengrass core software includes a message manager object, Lambda runtime, local copy service for IoT Thing (or device) shadows, and a deployment agent to manage Greengrass group configuration.\n* **Greengrass groups** are containers for selected IoT devices settings, subscriptions and associated Lambda functions.  In a Greengrass group a device is either a Greengrass core or an IoT device which will be connected that particular Greengrass core.\n* The Greengrass core SDK enables Lambda functions to interact with the AWS Greengrass core on which they run in order to publish messages, interact with the local Thing Shadows service, or invoke other deployed Lambda functions.\n* The AWS Greengrass Core SDK only supports sending MQTT messages with QoS = 0.\n* Shown below is a [diagram](http://docs.aws.amazon.com/greengrass/latest/developerguide/what-is-gg.html) which shows the architecture of AWS IoT Greengrass services:\n\n![IoT Greengrass](http://docs.aws.amazon.com/greengrass/latest/developerguide/images/greengrass.png)\n\n\n[Back to top :arrow_up:](#table-of-contents)\n### IoT Alternatives and Lock-in\n\n- \tAWS, Microsoft and Google have all introduced IoT-specific sets of cloud services since late 2015. AWS was first, moving their IoT services to [general availability](https://aws.amazon.com/blogs/aws/aws-iot-now-generally-available/) in Dec 2015. Microsoft released their set of IoT services for Azure in [Feb 2016](https://azure.microsoft.com/en-us/updates/generally-available-microsoft-azure-iot-hub/).  Google has only previewed, but not released their IoT services [Android Things](https://developer.android.com/things/index.html) and [Weave](https://developers.google.com/weave/).\n- \tIssues of lock-in center around your devices —  [protocols](http://www.postscapes.com/internet-of-things-protocols/) (for example MQTT, AMQP), message formats (such as, JSON vs. Hex...) and security (certificates).\n\n[Back to top :arrow_up:](#table-of-contents)\n### IoT Tips\n\n- \t**Getting started with Buttons:** One way to start is to use an [**AWS IoT Button**](https://aws.amazon.com/iot/button/).  AWS provides a number of code samples for use with their IoT Button, you can use the AWS IoT console, click the “connect AWS IoT button” link and you'll be taken to the  AWS Lambda console.  There you fill out your button’s serial number to associate it with a Lambda. (As of this writing, AWS IoT buttons are only available for sale in the US.)\n- \t**Connections and protocols:** It is important to understand the details of about the devices you wish to connect to the AWS IoT service, including how you will secure the device connections, the device protocols, and more. Cloud vendors differ significantly in their support for common IoT protocols, such as MQTT, AMQP, XMPP. AWS IoT supports **secure MQTT**, **WebSockets** and **HTTPS**.\n- \tSupport for **device security** via certificate processing is a key differentiator in this space.  In August 2016, AWS added [just-in-time registrations](https://aws.amazon.com/blogs/iot/just-in-time-registration-of-device-certificates-on-aws-iot/) for IoT devices to their services.\n- \t**Combining with other services:** It’s common to use other AWS services, such as AWS Lambda, Kinesis and DynamoDB, although this is by no means required.  Sample IoT application reference architectures are in this [screencast](https://www.youtube.com/watch?v=0Izh6ySpwb8/).\n- \t**Testing tools:**\n    *\tTo get started, AWS includes a lightweight MQTT client in the AWS IoT console. Here you can create and test sending and receiving messages to and from various MQTT topics.\n    * \tWhen testing locally, if using MQTT, it may be helpful to download and use the open source [Mosquitto broker](https://mosquitto.org/download/) tool for local testing with devices and/or device simulators\n    * \tUse this [MQTT load simulator](https://github.com/awslabs/aws-iot-mqtt-load-generator) to test device message load throughout your IoT solution.\n\n[Back to top :arrow_up:](#table-of-contents)\n### IoT Gotchas and Limitations\n\n- \t🔸**IoT protocols:** It is important to verify the exact type of support for your particular IoT device message protocol. For example, one commonly used IoT protocol is [MQTT](https://www.ibm.com/developerworks/community/blogs/5things/entry/5_things_to_know_about_mqtt_the_protocol_for_internet_of_things?lang=en). Within MQTT there are [three possible levels of QoS in MQTT](https://dzone.com/articles/internet-things-mqtt-quality).  AWS IoT supports MQTT [QoS 0](http://docs.aws.amazon.com/iot/latest/developerguide/protocols.html) (fire and forget, or at most once) and QoS 1(at least once, or includes confirmation), but *not* QoS 2 (exactly once, requires 4-step confirmation).  This is important in understanding how much code you’ll need to write for your particular application message resolution needs.  Here is a [presentation about the nuances of connecting](http://www.slideshare.net/AmazonWebServices/overview-of-iot-infrastructure-and-connectivity-at-aws-getting-started-with-aws-iot).\n- \t🔸The ecosystems to match **IAM users or roles** to **IoT policies** and their associated authorized AWS IoT devices are immature. Custom coding to enforce your security requirements is common.\n- \t❗A common mistake is to misunderstand the importance of IoT **device** **security**.  It is imperative to associate *each* device with a unique certificate (public key). You can generate your own certificates and upload them to AWS, or you can use AWS generated IoT device certificates. It’s best to read and understand AWS’s own guidance on this [topic](http://www.slideshare.net/AmazonWebServices/best-practices-of-iot-in-the-cloud).\n- \t🔸There is only one **AWS IoT Gateway** (endpoint) per AWS account. For production scenarios, you’ll probably need to set up multiple AWS accounts in order to separate device traffic for development, test and production. It’s interesting to note that the [Azure IoT Gateway](https://azure.microsoft.com/en-us/documentation/articles/iot-hub-protocol-gateway/) supports configuration of multiple endpoints, so that a single Azure account can be used with separate pub/sub endpoints for development, testing and production\n- \t🔸**Limits:** Be aware of [limits](http://docs.aws.amazon.com/iot/latest/developerguide/iot-limits.html), including device message size, type, frequency, and number of AWS IoT rules.\n\n[Back to top :arrow_up:](#table-of-contents)\n### IoT Code Samples\n\n- \t[Simple Beer Service](https://github.com/awslabs/simplebeerservice) is a surprisingly useful code example using AWS IoT, Lambda, etc.\n- \t[IoT-elf](https://github.com/awslabs/aws-iot-elf) offers clean Python sample using the AWS IoT SDK.\n- \t[IoT Button projects](https://www.hackster.io/AmazonWebServices/products/aws-iot-button) on Hackster include many different code samples for projects.\n- \t[5 IoT code examples](https://github.com/awslabs/aws-iot-examples/): a device simulator, MQTT sample, just in time registration, truck simulator, prediction data simulator.\n- \t[AWS Alexa trivia voice example](https://developer.amazon.com/public/community/post/TxDJWS16KUPVKO/New-Alexa-Skills-Kit-Template:-Build-a-Trivia-Skill-in-under-an-Hour) is a quick-start using Alexa voice capability and Lambda.\n- \tSome Raspberry Pi examples include the [Beacon project](https://github.com/araobp/beacon/blob/master/README.md), [Danbo](https://libraries.io/github/awslabs/aws-iot-demo-for-danbo), and [GoPiGo](https://github.com/awslabs/aws-iotbot).\n\nSES\n---\n\n### SES Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/ses/) ∙ [Documentation](https://aws.amazon.com/documentation/ses/) ∙ [FAQ](https://aws.amazon.com/ses/faqs/) ∙ [Pricing](https://aws.amazon.com/ses/pricing/)\n-\t**SES** (or Simple Email Service) is a service that exposes SMTP endpoints for your application to directly integrate with.\n\n[Back to top :arrow_up:](#table-of-contents)\n### SES Tips\n\n-\t🔹**Bounce Handling:** Make sure you handle this early enough. Your ability to send emails can be removed if SES sees [too many bounces](http://docs.aws.amazon.com/ses/latest/DeveloperGuide/best-practices-bounces-complaints.html).\n-\t🔹**Credentials:** Many developers get confused between [SES credentials](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/using-credentials.html) and AWS API keys. Make sure to enter [SMTP credentials](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html) while using the SMTP APIs.\n\n[Back to top :arrow_up:](#table-of-contents)\n### SES Gotchas and Limitations\n\n-\t🔸**Internet Access:** SES SMTP endpoints are on the Internet and will not be accessible from a location without Internet access (e.g. a private subnet without NAT gateway route in the routing table). In such a case, set up an SMTP relay instance in a subnet with Internet access and configure your application to send emails to this SMTP relay instance rather than SES. The relay should have a [forwarding rule to send all emails to SES](http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-smtp-existing-server.html)). ❗If you are using a proxy instead of a NAT, confirm that your proxy service supports SMTP.\n\nCertificate Manager\n-------------------\n\n### Certificate Manager Basics\n\n- 📒 [Homepage](https://aws.amazon.com/certificate-manager/) ∙ [User guide](http://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) ∙ [FAQ](https://aws.amazon.com/certificate-manager/faqs/) ∙ [Pricing](https://aws.amazon.com/certificate-manager/pricing/)\n- Use the **Certificate Manager** to manage SSL/TLS certificates in other AWS services.\n- Supports importing existing certificates as well as issuing new ones.\n- Provides Domain Validated (DV) certificates. [Validation](http://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate.html) can be done in two ways. The first (and recommended) way is [via DNS](https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-dns.html). If the zone lives within Route 53 and the user has access, the necessary record can be added in the console via a single click during the certificate request process. If the zone is not within Route 53 the user is required to update DNS manually. This is still preferred to the second way, which requires more user interaction, and is done by sending an email to 3 contact addresses in WHOIS and 5 common addresses for the domain, for each domain name present in the request.\n- ACM will attempt to automatically [renew](http://docs.aws.amazon.com/acm/latest/userguide/how-domain-validation-works.html) a certificate issued by Amazon. It will first attempt to connect to the domain on HTTPS and check that the certificate used by the domain is the same with the certificate that it intends to renew. Failing that, it will check the DNS record used previously for validation. Failing that, ACM will attempt manual validation by sending emails to all domains in the certificate.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Certificate Manager Alternatives and Lock-in\n\n- ⛓Certificates issued by the Certificate Manager can’t be used outside of the services that support it. Imported certificates, however, can still be used elsewhere.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Certificate Manager Tips\n\n- 🔹**Supported services:** Managed [Load Balancers](#load-balancers), [CloudFront](#cloudfront), [API Gateway](#api-gateway) and [Elastic Beanstalk](https://aws.amazon.com/elasticbeanstalk/).\n- 🔸During the domain validation process, if DNS validation is unsuccessful Certificate Manager will send an email to every contact address specified in the domain’s WHOIS record and up to five common administrative addresses. Some anti-spam filters can mark emails as spam because of this. You should check the spam folder of your email if you don’t receive a confirmation email.\n- 🔹 Setting up a certificate for a test domain you don't have email set up on? You can now use DNS validation instead.\n- 🔹Remember when requesting a wildcard domain that the request will not be valid for the level just below the wildcard, or any subdomains preceding the wildcard. Take for example an approved, issued certificate for `*.bar.example.com`. This would be valid for `foo.bar.example.com` but not `bar.example.com`. Likewise it would also not be valid for `www.bar.foo.example.com`. You would need to add each of these domains to the certificate request.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Certificate Manager Gotchas and Limitations\n\n- 🔸In order to use **Certificate Manager** for CloudFront distributions, the certificate must be issued or imported from us-east-1 (N. Virginia) region.\n- 🔸Certificates used with Elastic Load Balancers must be issued in the same region as the load balancer. Certificates can not be moved or copied between regions, as of July 2017. If a domain uses load balancers present in multiple regions, a different certificate must be requested for each region.\n- 🔸**IoT** has its [own way](http://docs.aws.amazon.com/iot/latest/developerguide/create-device-certificate.html) of setting up certificates.\n- 🔸By default the maximum number of domains per certificate is 10. You can get this limit increased to a maximum of 100 by contacting AWS support. **Note** for every different domain you have on the requested cert, you'll need to press accept on an email sent to that domain. For example if you request a cert with 42 different domains or sub domains, you'll need to press accept on 42 different links.\n\t- 🔹If you request a limit increase to AWS support for this, they will respond to you asking to confirm this. Bypass this by saying in the body of your initial request:\n```\"I acknowledge at the moment, there is no method to add or remove a name from a certificate. Instead, you must request a new certificate with the revised namelist and you must then re-approve all of the names in the certificate, even if they'd been previously approved.\"```\n- 🔸There is no way at the moment to add or remove a domain to/from an existing certificate. You must request a new certificate and re-approve it from each of the domains requested.\n\nWAF\n-------------------\n\n### WAF Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/waf/) ∙ [Documentation](https://aws.amazon.com/documentation/waf/) ∙ [FAQ](https://aws.amazon.com/waf/faq/) ∙ [Pricing](https://aws.amazon.com/waf/pricing)\n- WAF (Web Application Firewall) is used in conjunction with the CloudFront and ALB services to inspect and block/allow web requests based on user-configurable conditions.\n- HTTPS and HTTP requests are supported with this service.\n- WAF's strength is in detecting malicious activity based on pattern-matching inputs for attacks such as SQL injections, XSS, etc.\n- WAF supports inspection of requests [received through both IPv6 and IPv4](https://aws.amazon.com/about-aws/whats-new/2016/10/ipv6-support-for-cloudfront-waf-and-s3-transfer-acceleration/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### WAF Tips\n\n- Getting a WAF API call history can be done through CloudTrail. This is enabled through the CloudTrail console.\n- It's also possible to get [full\n  logs of all the web requests inspected](https://aws.amazon.com/about-aws/whats-new/2018/08/aws-waf-launches-new-comprehensive-logging-functionality/)\n\n[Back to top :arrow_up:](#table-of-contents)\n### WAF Gotchas and Limitations\n\n- As of May 2019, AWS WAF is  available on Amazon CloudFront and in 12 commercial AWS regions: US East (N. Virginia), US East (Ohio), US West (Oregon), US West (N. California), EU (Ireland), EU (Frankfurt), EU (London), EU (Stockholm), Asia Pacific (Tokyo), Asia Pacific (Sydney), Asia Pacific (Singapore), and Asia Pacific (Seoul).\n\n\nOpsWorks\n-------------------\n\n### OpsWorks Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/opsworks/) ∙ [Documentation](https://aws.amazon.com/documentation/opsworks/) ∙ [FAQ](https://aws.amazon.com/opsworks/faqs/) ∙ Pricing: [Stacks](https://aws.amazon.com/opsworks/stacks/pricing/), [Chef Automate](https://aws.amazon.com/opsworks/chefautomate/pricing/), [Puppet Enterprise](https://aws.amazon.com/opsworks/puppetenterprise/pricing/)\n- OpsWorks is a configuration management service that uses [Chef](https://www.chef.io/chef/) or [Puppet](https://www.puppet.com) configuration management. It is broken out into three different services:\n  - [OpsWorks Stacks](https://aws.amazon.com/opsworks/stacks/): The service lets you configure and launch stacks specific to your application's needs, and allows you to automate application deployments. Chef runs can be performed manually via the Execute Cookbooks command, otherwise they are only run as part of lifecycle events.\n    - OpsWorks Stacks differs from standard configuration management services in that it also allows you to perform some infrastructure and application automation (such as creating Amazon EC2 instances and deploying applications via Chef cookbooks).\n  - [OpsWorks for Chef Automate](https://aws.amazon.com/opsworks/chefautomate/): This service launches a dedicated Chef Automate server in your account, which can be used to associate nodes, upload cookbook code, and configure systems. Automated patching, backups, OS updates, and minor Chef version upgrades are provided as part of the service. An AWS API is provided for associating/disassociating nodes. Chef runs can be scheduled on nodes using the [chef-client cookbook](https://supermarket.chef.io/cookbooks/chef-client).\n  - [OpsWorks for Puppet Enterprise](https://aws.amazon.com/opsworks/puppetenterprise/): This service launches a dedicated Puppet Master in your account, which can be used to associate nodes, upload modules, and configure systems. Automated patching, backups, OS updates, and minor Puppet version upgrades are provided as part of the service. An AWS API is provided for associating/disassociating nodes. By default, the Puppet agent will run automatically every 30 minutes on associated nodes.\n- OpsWorks for Chef Automate and OpsWorks for Puppet Enterprise are strictly designed for configuration management, and do not provision infrastructure outside the Chef Server/Puppet Master that is created in our account.\n- All three OpsWorks services support managing both Amazon EC2 and on-premises infrastructure, however the implementation details differ slightly.\n  - OpsWorks Stacks allows you to register instances and install the OpsWorks Agent to connect to your stack.\n  - OpsWorks for Chef Automate and OpsWorks for Puppet Enterprise allow you to associate new or existing infrastructure using either the opsworks-cm:AssociateNode API action or the vendor-supported method for associating nodes to Chef Server or Puppet Enterprise.\n- Although OpsWorks will let you work with common Chef recipes or Puppet modules when creating your stacks, creating custom recipes will require familiarity with Chef or Puppet syntax. Chef/Puppet code is not supported as part of AWS Support.\n- As of December 2016, OpsWorks Stacks supports Chef versions [12, 11.10.4, 11.4.4 and 0.9.15.5](http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook.html).\n- As of December 2016, OpsWorks for Chef Automate uses [Chef Server version 12.11.1](http://docs.aws.amazon.com/opsworks/latest/userguide/welcome_opscm.html) This is the current stable version of Chef.\n- [Berkshelf](http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-chef11-10.html#workingcookbook-chef11-10-berkshelf)can be used  with Chef stacks of version 11.10 and later for managing cookbooks and their respective dependencies. However, on Chef 12.x stacks, Berkshelf must be installed by the stack administrator.\n- Running your own Chef environment may be an alternative to consider - some considerations are listed [in this Bitlancer article.](http://www.bitlancer.com/blog/2015/10/05/opsworks-vs-chef.html)\n\n[Back to top :arrow_up:](#table-of-contents)\n### OpsWorks Alternatives and Lock-in\n\n- Major competitors in Configuration Management include:\n  - [Chef](https://chef.io)\n  - [Puppet](https://puppet.com)\n  - [Ansible](https://www.ansible.com).\n\n[Back to top :arrow_up:](#table-of-contents)\n### OpsWorks Tips\n\n- OpsWorks Stacks and OpsWorks for Chef Automate use Chef cookbooks for configuration. Chef provides free training to learn syntax, best practices, etc. at [https://learn.chef.io](https://learn.chef.io).\n- OpsWorks for Puppet Enterprise uses Puppet manifests for configuration. Puppet provides a very useful learning VM for download at [https://learn.puppet.com/](https://learn.puppet.com/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### OpsWorks Gotchas and Limitations\n\n- OpsWorks Stacks is not available in the following regions:\n  - Montreal\n  - GovCloud\n  - Beijing\n- OpsWorks for Chef Automate and OpsWorks for Puppet Enterprise are not available in the following regions:\n  - Montreal\n  - Sao Paulo\n  - GovCloud\n  - London\n  - Paris\n  - Seoul\n  - Mumbai\n\nBatch\n-------------------\n\n### Batch Basics\n\n-\t📒 [Homepage](https://aws.amazon.com/batch/) ∙ [Documentation](https://aws.amazon.com/documentation/batch/) ∙ [FAQ](https://aws.amazon.com/batch/faqs/) ∙ [Pricing](https://aws.amazon.com/batch/pricing/)\n- **AWS Batch** is a service that offers an environment to run batch computing jobs. The service dynamically provisions the optimal compute resources needed by the jobs based on their resource requirements, and can scale up to hundreds of thousands of [jobs](http://docs.aws.amazon.com/batch/latest/userguide/jobs.html).\n- These batch workloads have access to all other AWS services and features.\n- AWS Batch, coupled with [spot instances](https://aws.amazon.com/blogs/compute/cost-effective-batch-processing-with-amazon-ec2-spot/) can help run the jobs when appropriate capacity is available, providing for optimal utilization of compute resources.\n- The batch workloads are built as a [Docker](https://www.docker.com/) Image. These images can then pushed to the [EC2 Container Registry](https://aws.amazon.com/ecr/) (ECR), or any private repository that can be accessed from AWS.\n- A [Job Definition](http://docs.aws.amazon.com/batch/latest/userguide/job_definitions.html) has the workload's Docker Image URI, and also lets the users specify the environment details like vCPUs, memory, volume mappings, environment variables, parameters, retry strategy, container properties, and the job's IAM role.\n- The [Compute Environments](http://docs.aws.amazon.com/batch/latest/userguide/compute_environments.html) are EC2 clusters that provide the runtime for the batch workloads to execute in.\n- AWS Batch provides managed, as well as unmanaged compute environments. The Managed Environments are provisioned and managed by AWS, while the Unmanaged Environments are managed by the customers.\n- The Job Definitions are submitted to [Job Queue(s)](http://docs.aws.amazon.com/batch/latest/userguide/job_queues.html) for execution. Each queue has a priority, and has at least one Compute Environment associated with it.\n- AWS Batch uses [ECS](https://aws.amazon.com/ecs/) to execute the containerized jobs.\n\n[Back to top :arrow_up:](#table-of-contents)\n### Batch Tips\n\n- AWS Batch supports prioritization of jobs via the Job Queue Priority. Higher the number - higher the priority.\n- AWS Batch supports launching the Compute Environment into specific VPC and subnets.\n- A Compute Environment is same as an [ECS Cluster](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_clusters.html).\n- There is no additional cost for AWS Batch. You only pay the cost associated with the AWS Services being used - like EC2 Instances and any resources consumed by the batch jobs.\n- Associate [IAM Roles and policies](http://docs.aws.amazon.com/batch/latest/userguide/IAM_policies.html) with the Compute Environment to enable the containers access to other AWS resources.\n- 🔹 Use Unmanaged Compute Environments if you need specialized resources like Dedicated Hosts, or [EFS](https://aws.amazon.com/efs/).\n\nSQS\n-------------------\n\n### SQS Basics\n\n- 📒  [_Homepage_](https://aws.amazon.com/sqs/) ∙ [_Documentation_](https://aws.amazon.com/documentation/sqs/) ∙ [_FAQ_](https://aws.amazon.com/sqs/faqs/) ∙ [_Pricing_ ](https://aws.amazon.com/sqs/pricing/)\n- SQS is a highly scalable, fully managed message queuing service from AWS.\n- SQS supports the pull model, where the producers *queue* the messages, and the consumers pull messages off the queue.\n- SQS provides a message visibility timeout, during which the message being processed will not be delivered to other consumers. If the consumer does not delete the message after processing, the message becomes available to other consumers upon reaching the message visibility timeout. This parameter is called VisibilityTimeout.\n- Each message can have up to 10 custom fields, or attributes.\n- SQS allows producers to set up to 15 minutes of delay before the messages are delivered to the consumers. This parameter is called DelaySeconds.\n- There are two types of queues supported by SQS -\n    - Standard Queues\n        - Guarantee **at least once** delivery of the messages.\n        - Do not retain the order of delivery of the messages.\n    - FIFO Queues\n        - Guarantee **only once** delivery of the messages\n        - Guarantee the order of the delivery of the messages\n- SQS supports fine grained access to various API calls and Queues via IAM policies.\n- The messages that fail to process can be put in a dead letter queue.\n\n[Back to top :arrow_up:](#table-of-contents)\n### SQS Alternatives and Lock-In\n\n- Alternatives to SQS include [Kafka](https://kafka.apache.org/), [RabbitMQ](https://www.rabbitmq.com/), [ActiveMQ](http://activemq.apache.org/) and others.\n- Google Cloud Platform has Pub/Sub, and Azure has Azure Queue Service.\n- [SQS vs SNS](#sns-alternatives-and-lock-in)\n\n[Back to top :arrow_up:](#table-of-contents)\n### SQS Tips\n\n- SNS can be used in combination of SQS to build a “fan out” mechanism by having an SQS Queue subscribe to the SNS topic.\n- SQS supports encryption using AWS KMS.\n- Cloudwatch alarms can be creating using [various SQS metrics](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/sqs-metricscollected.html) to trigger autoscaling actions and/or notifications.\n\n[Back to top :arrow_up:](#table-of-contents)\n### SQS Gotchas and Limitations\n\n- 🔸 SQS does not have a VPC endpoint (unlike S3 and DynamoDB), so SQS will need to be accessed using public SQS API endpoints.\n- 🔸 FIFO Queues are limited to 300 API calls per second.\n- 🔸 FIFO Queues cannot subscribe to an SNS topic.\n- 🔸 Standard Queues can deliver duplicate messages regardless of the visibility window. If only-once delivery is your only choice, then use FIFO queues, or build an additional layer to de-dupe the messages.\n- 🔸 You can send/receive messages in batch, however, there can only be maximum of 10 messages in a batch.\n\n\nSNS\n---------------------\n\n### SNS Basics\n\n- 📒  [_Homepage_](https://aws.amazon.com/sns/) ∙ [_Documentation_](https://aws.amazon.com/documentation/sns/) ∙ [_FAQ_](https://aws.amazon.com/sns/faqs/) ∙ [_Pricing_](https://aws.amazon.com/sns/pricing/)\n- **SNS** (Simple Notification Service) is a pub/sub based, highly scalable, and fully managed messaging service that can also be used for mobile notifications.\n- SNS can push the messages down to the subscribers via [SMS](http://docs.aws.amazon.com/sns/latest/dg/SMSMessages.html), [Email](http://docs.aws.amazon.com/sns/latest/dg/SubscribeTopic.html), [SQS](http://docs.aws.amazon.com/sns/latest/dg/SendMessageToSQS.html), and [HTTP/S](http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html) transport protocols.\n- Producers publish messages to a SNS Topics, which can have many subscribers.\n- Each subscription has an associated [protocol](http://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html), which is used to notify the subscriber.\n- A copy of the message is sent to each subscriber using the associated protocol.\n- SNS can also [invoke lambda functions](http://docs.aws.amazon.com/sns/latest/dg/sns-lambda.html).\n\n[Back to top :arrow_up:](#table-of-contents)\n### SNS Alternatives and Lock-In\n\n- Popular alternatives to SNS are [Kafka](https://kafka.apache.org/), [Notification Hubs](https://azure.microsoft.com/en-us/services/notification-hubs/) on Azure, and [Pub/Sub](https://cloud.google.com/pubsub/docs/overview) on Google Cloud.\n- **SNS vs SQS:**\n    - Both SNS and SQS are highly scalable, fully managed messaging services provided by AWS.\n    - SQS supports a *pull* model, while SNS supports a *push* model. Consumers have to pull messages from an SQS Queue, while they're pushed the message from an SNS Topic.\n    - An SQS message is intended to be processed by only one subscriber, while SNS topics can have many subscribers.\n    - After processing, the SQS message is deleted from the queue by the subscriber to avoid being re-processed.\n    - An SNS message is *pushed* to all subscribers of the topic at the same time, and is not available for deletion at the topic.\n    - SNS supports multiple transport protocols of delivery of the messages to the subscribers, while SQS subscribers have to pull the messages off the queue over HTTPS.\n\n[Back to top :arrow_up:](#table-of-contents)\n### SNS Tips\n\n- [Fan-out](http://docs.aws.amazon.com/sns/latest/dg/SNS_Scenarios.html) architecture can be achieved by having multiple subscribers for a topic. This is particularly useful when events have to be fanned out to multiple, isolated systems.\n- SNS topics can be used to power [webhooks](https://en.wikipedia.org/wiki/Webhook) with [backoff support](http://docs.aws.amazon.com/sns/latest/dg/DeliveryPolicies.html) to subscribers over HTTP/S.\n- [SQS queues](http://docs.aws.amazon.com/sns/latest/dg/SendMessageToSQS.html) can subscribe to SNS topics.\n- SNS is used to manage notifications for other AWS services like [Autoscaling Groups](http://docs.aws.amazon.com/autoscaling/latest/userguide/ASGettingNotifications.html)' notifications, [CloudWatch Alarms](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/US_SetupSNS.html), etc.\n- SNS is frequently used as “glue” between disparate systems— such as GitHub and AWS services.\n\n[Back to top :arrow_up:](#table-of-contents)\n### SNS Gotchas and Limitations\n\n- 🔸 HTTP/S subscribers of SNS topics need to have public endpoints, as SNS does not support calling private endpoints (like those in a private subnet within a VPC).\n- 📜 In a fan-out scenario, [SSE-enabled SQS](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html) subscribers of an SNS topic [will not receive](https://lobster1234.github.io/2017/10/14/fan-out-with-sns-and-sqs-gotcha/) the messages sent to the topic.\n\nHigh Availability\n-----------------\n\nThis section covers tips and information on achieving [high availability](https://en.wikipedia.org/wiki/High_availability).\n\n\n\n### High Availability Tips\n\n-\tAWS offers two levels of redundancy, [regions and availability zones (AZs)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-regions-availability-zones).\n-\tWhen used correctly, regions and zones do allow for high availability. You may want to use non-AWS providers for larger business risk mitigation (i.e. not tying your company to one vendor), but reliability of AWS across regions is very high.\n-\t**Multiple regions:** Using multiple regions is complex, since it’s essentially like managing completely separate infrastructures. It is necessary for business-critical services with the highest levels of redundancy. However, for many applications (like your average consumer startup), deploying extensive redundancy across regions may be overkill.\n-\tThe [High Scalability Blog](http://highscalability.com/blog/2016/1/11/a-beginners-guide-to-scaling-to-11-million-users-on-amazons.html) has a good guide to help you understand when you need to scale an application to multiple regions.\n-\t🔹**Multiple AZs:** Using AZs wisely is the primary tool for high availability!\n\t-\tA typical single-region high availability architecture would be to deploy in two or more availability zones, with load balancing in front, as in [this AWS diagram](http://media.amazonwebservices.com/architecturecenter/AWS_ac_ra_ftha_04.pdf).\n\t-\tThe bulk of outages in AWS services affect one zone only. There have been rare outages affecting multiple zones simultaneously (for example, the [great EBS failure of 2011](http://aws.amazon.com/message/65648/)) but in general most customers’ outages are due to using only a single AZ for some infrastructure.\n\t-\tConsequently, design your architecture to minimize the impact of AZ outages, especially single-zone outages.\n\t-\tDeploy key infrastructure across at least two or three AZs. Replicating a single resource across more than three zones often won’t make sense if you have other backup mechanisms in place, like S3 snapshots.\n\t-\tA second or third AZ should significantly improve availability, but additional reliability of 4 or more AZs may not justify the costs or complexity (unless you have other reasons like capacity or Spot market prices).\n\t-\t💸Watch out for **cross-AZ traffic costs**. This can be an unpleasant surprise in architectures with large volume of traffic crossing AZ boundaries.\n\t-\tDeploy instances evenly across all available AZs, so that only a minimal fraction of your capacity is lost in case of an AZ outage.\n\t-\tIf your architecture has single points of failure, put all of them into a single AZ. This may seem counter-intuitive, but it minimizes the likelihood of any one SPOF to go down on an outage of a single AZ.\n-\t**EBS vs instance storage:** For a number of years, EBSs had a poorer track record for availability than instance storage. For systems where individual instances can be killed and restarted easily, instance storage with sufficient redundancy could give higher availability overall. EBS has improved, and modern instance types (since 2015) are now EBS-only, so this approach, while helpful at one time, may be increasingly archaic.\n-\tBe sure to [use and understand CLBs/ALBs](#load-balancers) appropriately. Many outages are due to not using load balancers, or misunderstanding or misconfiguring them.\n\n[Back to top :arrow_up:](#table-of-contents)\n### High Availability Gotchas and Limitations\n\n-\t🔸**AZ naming** differs from one customer account to the next. Your “us-west-1a” is not the same as another customer’s “us-west-1a” — the letters are assigned to physical AZs randomly per account. This can also be a gotcha if you have multiple AWS accounts. Note that Zone IDs are consistent between accounts, and can be used to reliably align between AWS accounts.\n-\t🔸💸**Cross-AZ traffic** is not free. At large scale, the costs add up to a significant amount of money. If possible, optimize your traffic to stay within the same AZ as much as possible.\n\nBilling and Cost Management\n---------------------------\n\n### Billing and Cost Visibility\n\n-\tAWS offers a [**free tier**](https://aws.amazon.com/free/) of service, that allows very limited usage of resources at no cost. For example, a micro instance and small amount of storage is available for no charge. Many services are only eligible for the free tier for the first twelve months that an account exists, but other services offer a free usage tier indefinitely. (If you have an old account but starting fresh, sign up for a new one to qualify for the free tier.) [AWS Activate](https://aws.amazon.com/activate/) extends this to tens of thousands of dollars of free credits to startups in [certain funds or accelerators](https://aws.amazon.com/activate/portfolio-detail/).\n-\tYou can set [**billing alerts**](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/free-tier-alarms.html) to be notified of unexpected costs, such as costs exceeding the free tier. You can set these in a [granular way](https://wblinks.com/notes/aws-tips-i-wish-id-known-before-i-started/#billing).\n-\tAWS offers [Cost Explorer](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-explorer-what-is.html), a tool to get better visibility into costs.\n-\tUnfortunately, the AWS console and billing tools are rarely enough to give good visibility into costs. For large accounts, the AWS billing console can time out or be too slow to use.\n-\t**Tools:**\n\t-\t🔹Enable [billing reports](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/detailed-billing-reports.html) and install an open source tool to help manage or monitor AWS resource utilization. [**Teevity Ice**](https://github.com/Teevity/ice) (originally written by Netflix) is probably the first one you should try. Check out [docker-ice](https://github.com/jonbrouse/docker-ice) for a Dockerized version that eases installation.\n\t-\t🔸One challenge with Ice is that it doesn’t cover amortized cost of reserved instances.\n\t-\tOther tools include [Security Monkey](https://github.com/Netflix/security_monkey) and [Cloud Custodian](https://github.com/capitalone/cloud-custodian).\n\t-\tUse [AWS Simple Monthly Calculator](https://calculator.s3.amazonaws.com/index.html) to get an estimate of usage charges for AWS services based on certain information you provide. Monthly charges will be based on your actual usage of AWS services, and may vary from the estimates the Calculator has provided.\n-\t**Third-party services:** Several companies offer services designed to help you gain insights into expenses or lower your AWS bill, such as [Cloudability](https://www.cloudability.com/), [CloudHealth Technologies](https://www.cloudhealthtech.com/), and [ParkMyCloud](http://www.parkmycloud.com/). Some of these charge a percentage of your bill, which may be expensive. See the [market landscape](#tools-and-services-market-landscape).\n-\tAWS’s [Trusted Advisor](https://aws.amazon.com/premiumsupport/trustedadvisor/) is another service that can help with cost concerns.\n-\tDon’t be shy about asking your account manager for guidance in reducing your bill. It’s their job to keep you happily using AWS.\n-\t**Tagging for cost visibility:** As the infrastructure grows, a key part of managing costs is understanding where they lie. It’s strongly advisable to [tag resources](https://aws.amazon.com/blogs/aws/resource-groups-and-tagging/), and as complexity grows, group them effectively. If you [set up billing allocation appropriately](http://aws.amazon.com/blogs/aws/aws-cost-allocation/), you can then get visibility into expenses according to organization, product, individual engineer, or any other way that is helpful.\n-\tIf you need to do custom analysis of raw billing data or want to feed it to a third party cost analysis service, [enable](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/detailed-billing-reports.html#turnonreports) the [detailed billing report](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/detailed-billing-reports.html#detailed-billing-report) feature.\n-\tMultiple Amazon accounts can be linked for billing purposes using the [Consolidated Billing](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/consolidated-billing.html) feature. Large enterprises may need complex billing structures depending on ownership and approval processes.\n-\tMultiple Amazon accounts can be managed centrally using [AWS Organizations](https://aws.amazon.com/organizations/).\n\n[Back to top :arrow_up:](#table-of-contents)\n### AWS Data Transfer Costs\n\n-\tFor deployments that involve significant network traffic, a large fraction of AWS expenses are around data transfer. Furthermore, costs of data transfer, within AZs, within regions, between regions, and into and out of AWS and the internet vary significantly depending on deployment choices.\n-\tSome of the most common gotchas:\n\t-\t🔸*AZ-to-AZ traffic:* Note EC2 traffic between AZs is effectively the same as between regions. For example, deploying a Cassandra cluster across AZs is helpful for [high availability](#high-availability), but can hurt on network costs.\n\t-\t🔸*Using public IPs when not necessary:* If you use an Elastic IP or public IP address of an EC2 instance, you will incur network costs, even if it is accessed locally within the AZ.\n\t-\t🔸*Managed NAT Gateway data processing:* Managed NAT Gateways are used to let traffic egress from private subnets--at a cost of 4.5¢ as a data processing fee layered on top of data transfer pricing. Past a certain point, running your own NAT instances becomes far more cost effective.\n\t-\t🔸*Some services do cross-AZ traffic for free:* Many AWS services you'd not consider on their own merits offer a hidden value of free cross-AZ data transfer. EFS, RDS, MSK, and others are examples of this.\n-\tThis figure gives an overview:\n\n![AWS Data Transfer Costs](figures/aws-data-transfer-costs.png)\n\n[Back to top :arrow_up:](#table-of-contents)\n### EC2 Cost Management\n\n-\tWith EC2, there is a trade-off between engineering effort (more analysis, more tools, more complex architectures) and spend rate on AWS. If your EC2 costs are small, many of the efforts here are not worth the engineering time required to make them work. But once you know your costs will be growing in excess of an engineer’s salary, serious investment is often worthwhile.\n-\tLarger instances aren’t necessarily priced higher in the spot market – therefore, you should look at the available options and determine which instances will be most cost effective for your jobs. See [Bid Advisor](https://aws.amazon.com/ec2/spot/bid-advisor/).\n-\t🔹**Spot instances:**\n\t-\tEC2 [Spot instances](https://aws.amazon.com/ec2/spot/) are a way to get EC2 resources at significant discount — often many times cheaper than standard on-demand prices — if you’re willing to accept the possibility that they be terminated with little to no warning.\n\t-\tUse Spot instances for potentially very significant discounts whenever you can use resources that may be restarted and don’t maintain long-term state.\n\t-\tThe huge savings that you can get with Spot come at the cost of a significant increase in complexity when provisioning and reasoning about the availability of compute capacity.\n\t-\tAmazon maintains Spot prices at a market-driven fluctuating level, based on their inventory of unused capacity. Prices are typically low but can [spike](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-limits.html#spot-bid-limit) very high. See the [price history](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html) to get a sense for this.\n\t-\tYou set a bid price high to indicate how high you’re willing to pay, but you only pay the going rate, not the bid rate. If the market rate exceeds the bid, your instance may be terminated.\n\t-\tPrices are per instance type and per availability zone. The same instance type may have wildly different price in different zones at the same time. Different instance types can have very different prices, even for similarly powered instance types in the same zone.\n\t-\tCompare prices across instance types for better deals.\n\t-\tUse Spot instances whenever possible. Setting a high bid price will assure your machines stay up the vast majority of the time, at a fraction of the price of normal instances.\n\t-\tGet notified up to two minutes before price-triggered shutdown by polling [your Spot instances’ metadata](https://aws.amazon.com/blogs/aws/new-ec2-spot-instance-termination-notices/), or by watching for [the termination CloudWatch event](https://aws.amazon.com/about-aws/whats-new/2018/01/amazon-ec2-spot-two-minute-warning-is-now-available-via-amazon-cloudwatch-events/).\n\t-\tMake sure your usage profile works well for Spot before investing heavily in tools to manage a particular configuration.\n-\t**Spot fleet:**\n\t-\tYou can realize even bigger cost reductions at the same time as improvements to fleet stability relative to regular Spot usage by using [Spot fleet](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet.html) to bid on instances across instance types, availability zones, and (through multiple Spot Fleet Requests) regions.\n\t-\tSpot fleet targets maintaining a specified (and weighted-by-instance-type) total capacity across a cluster of servers. If the Spot price of one instance type and availability zone combination rises above the weighted bid, it will rotate running instances out and bring up new ones of another type and location up in order to maintain the target capacity without going over target cluster cost.\n-\t**Spot usage best practices:**\n\t-\t**Application profiling:**\n\t\t-\tProfile your application to figure out its runtime characteristics. That would help give an understanding of the minimum cpu, memory, disk required. Having this information is critical before you try to optimize spot costs.\n\t\t-\tOnce you know the minimum application requirements, instead of resorting to fixed instance types, you can bid across a variety of instance types (that gives you higher chances of getting a spot instance to run your application).E.g., If you know that 4 cpu cores are enough for your job, you can choose any instance type that is equal or above 4 cores and that has the least Spot price based on history. This helps you bid for instances with greater discount (less demand at that point).\n\t-\t**Spot price monitoring and intelligence:**\n\t\t-\tSpot Instance prices fluctuate depending on instance types, time of day, region and availability zone. The AWS CLI tools and API allow you to describe Spot price metadata given time, instance type, and region/AZ.\n\t\t-\tBased on history of Spot instance prices, you could potentially build a myriad of algorithms that would help you to pick an instance type in a way that **optimizes cost**, **maximizes availability**, or **offers predictable performance**.\n\t\t-\tYou can also track the number of times an instance of certain type got taken away (out bid) and plot that in graphite to improve your algorithm based on time of day.\n\t-\t**Spot machine resource utilization:**\n\t\t-\tFor running spiky workloads (spark, map reduce jobs) that are schedule based and where failure is non critical, Spot instances become the perfect candidates.\n\t\t-\tThe time it takes to satisfy a Spot instance could vary between 2-10 mins depending on the type of instance and availability of machines in that AZ.\n\t\t-\tIf you are running an infrastructure with hundreds of jobs of spiky nature, it is advisable to start pooling instances to optimize for cost, performance and most importantly time to acquire an instance.\n\t\t-\tPooling implies creating and maintaining Spot instances so that they do not get terminated after use. This promotes re-use of Spot instances across jobs. This of course comes with the overhead of lifecycle management.\n\t\t-\tPooling has its own set of metrics that can be tracked to optimize resource utilization, efficiency and cost.\n\t\t-\tTypical pooling implementations give anywhere between 45-60% cost optimizations and 40% reduction in spot instance creation time.\n\t\t-\tAn excellent example of Pooling implementation described by Netflix ([part1](http://techblog.netflix.com/2015/09/creating-your-own-ec2-spot-market.html), [part2](http://techblog.netflix.com/2015/11/creating-your-own-ec2-spot-market-part-2.html)\\)\n-\t**Spot management gotchas**\n\t-\t🔸**Lifetime:** There is [no guarantee](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html) for the lifetime of a Spot instance. It is purely based on bidding. If anyone outbids your price, the instance is taken away. Spot is not suitable for time sensitive jobs that have strong SLA. Instances will fail based on demand for Spot at that time. AWS provides a [two-minute warning](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#spot-instance-termination-notices) before Amazon EC2 must terminate your Spot instance.\n\t-\t🔹**API return data:** - The Spot price API returns Spot prices of varying granularity depending on the time range specified in the api call.E.g If the last 10 min worth of history is requested, the data is more fine grained. If the last 2 day worth of history is requested, the data is more coarser. Do not assume you will get all the data points. There **will** be skipped intervals.\n\t-\t❗**Lifecycle management:** Do not attempt any fancy Spot management unless absolutely necessary. If your entire usage is only a few machines and your cost is acceptable and your failure rate is lower, do not attempt to optimize. The pain for building/maintaining it is not worth just a few hundred dollar savings.\n-\t**Reserved Instances:** allow you to get significant discounts on EC2 compute hours in return for a commitment to pay for instance hours of a specific instance type in a specific AWS region and availability zone for a pre-established time frame (1 or 3 years). Further discounts can be realized through “partial” or “all upfront” payment options.\n\t-\tConsider using Reserved Instances when you can predict your longer-term compute needs and need a stronger guarantee of compute availability and continuity than the (typically cheaper) Spot market can provide. However be aware that if your architecture changes your computing needs may change as well so long term contracts can seem attractive but may turn out to be cumbersome.\n\t-\tThere are two types of Reserved Instances - [Standard and Convertible](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/reserved-instances-types.html). If you purchase excess Standard Reserved Instances, you may offer to “sell back” unused Reserved Instances via the [Reserved Instance Marketplace](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-selling-guide.html), this allows you to potentially recoup the cost of unused EC2 compute instance hours by selling them to other AWS customers.\n\t-\tInstance reservations are not tied to specific EC2 instances - they are applied at the billing level to eligible compute hours as they are consumed across all of the instances in an account.\n\t-\t📜There have been scattered reports of Convertible RI purchases needing to be exercised in a block-- namely, if you buy five convertible RIs in one purchase, you can't convert just two of them. Reach out to your account manager for clarification if this may impact you.\n-\tIf you have multiple AWS accounts and have configured them to roll charges up to one account using the “Consolidated Billing” feature, you can expect *unused* Reserved Instance hours from one account to be applied to matching (region, availability zone, instance type) compute hours from another account.\n-\tIf you have multiple AWS accounts that are linked with Consolidated Billing, plan on using reservations, and want unused reservation capacity to be able to apply to compute hours from other accounts, you’ll need to create your instances in the availability zone with the same *name* across accounts. Keep in mind that when you have done this, your instances may not end up in the same *physical* data center across accounts - Amazon shuffles availability zones names across accounts in order to equalize resource utilization.\n-\tMake use of dynamic [Auto Scaling](#auto-scaling), where possible, in order to better match your cluster size (and cost) to the current resource requirements of your service.\n-\tIf you use RHEL instances and happen to have existing RHEL on-premise Red Hat subscriptions, then you can leverage Red Hat's [Cloud Access program](https://www.redhat.com/en/technologies/cloud-computing/cloud-access) to migrate a portion of your on-premise subscriptions to AWS, and thereby saving on AWS charges for RHEL subscriptions. You can either use your own self-created RHEL AMI's or Red Hat provided [Gold Images](https://access.redhat.com/articles/2962171) that will be added to your private AMI's once you sign up for Red Hat Cloud Access.\n\nFurther Reading\n---------------\n\nThis section covers a few unusually useful or “must know about” resources or lists.\n\n-\tAWS\n\t-\t[AWS In Plain English](https://www.expeditedssl.com/aws-in-plain-english): A readable overview of all the AWS services.\n\t-\t[Awesome AWS](https://github.com/donnemartin/awesome-aws): A curated list of AWS tools and software.\n\t-\t[AWS Tips I Wish I'd Known Before I Started](https://wblinks.com/notes/aws-tips-i-wish-id-known-before-i-started/): A list of tips from [Rich Adams](https://richadams.me/)\n\t-\t[AWS Whitepapers](https://aws.amazon.com/whitepapers/): A list of technical AWS whitepapers, covering topics such as architecture, security and economics.\n\t-\t[Last Week in AWS](https://lastweekinaws.com): A weekly email newsletter covering the latest happenings in the AWS ecosystem.\n\t-\t[AWS Geek](https://www.awsgeek.com): A blog by AWS Community Hero Jerry Hargrove, with notes and hand-drawn diagrams about various AWS services.\n-\tBooks\n\t-\t[Amazon Web Services in Action](https://www.manning.com/books/amazon-web-services-in-action)\n\t-\t[AWS Lambda in Action](https://www.manning.com/books/aws-lambda-in-action)\n\t-\t[Serverless Architectures on AWS](https://www.manning.com/books/serverless-architectures-on-aws)\n\t-\t[Serverless Single Page Apps](https://pragprog.com/book/brapps/serverless-single-page-apps)\n\t-\t[The Terraform Book](https://terraformbook.com/)\n\t-\t[AWS Scripted 2 book series](https://www.amazon.com/gp/product/B016QBB0GO)\n\t-\t[Amazon Web Services For Dummies](https://www.amazon.com/dp/1118571835)\n\t-\t[AWS System Administration](http://shop.oreilly.com/product/0636920027638.do)\n\t-\t[Python and AWS Cookbook](http://shop.oreilly.com/product/0636920020202.do)\n\t-\t[Resilience and Reliability on AWS](http://shop.oreilly.com/product/0636920026839.do)\n\t-\t[AWS documentation as Kindle ebooks](https://www.amazon.com/Amazon-Web-Services/e/B007R6MVQ6)\n-\tGeneral references\n\t-\t[AWS Well Architected Framework Guide](https://d0.awsstatic.com/whitepapers/architecture/AWS_Well-Architected_Framework.pdf): Amazon’s own 56 page guide to operational excellence - guidelines and checklists to validate baseline security, reliability, performance (including high availability) and cost optimization practices.\n\t-\t[Awesome Microservices](https://github.com/mfornos/awesome-microservices): A curated list of tools and technologies for microservice architectures. Worth browsing to learn about popular open source projects.\n\t-\t[Is it fast yet?](https://istlsfastyet.com/): Ilya Grigorik’s TLS performance overview\n\t-\t[High Performance Browser Networking](https://hpbn.co/): A full, modern book on web network performance; a presentation on the HTTP/2 portion is [here](https://docs.google.com/presentation/d/1r7QXGYOLCh4fcUq0jDdDwKJWNqWK1o4xMtYpKZCJYjM/edit?usp=sharing).\n\nDisclaimer\n----------\n\nThe authors and contributors to this content cannot guarantee the validity of the information found here. Please make sure that you understand that the information provided here is being provided freely, and that no kind of agreement or contract is created between you and any persons associated with this content or project. The authors and contributors do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions in the information contained in, associated with, or linked from this content, whether such errors or omissions result from negligence, accident, or any other cause.\n\nLicense\n-------\n\n[![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/)\n\nThis work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/).\n"
  },
  {
    "path": "admin/authors-info.yml",
    "content": "# This file is used to configure the \"ghizmo assemble-authors\" command.\n\nheader: |\n  This “Open Guide” is a collaborative effort.\n  It was begun and is led by [@jlevy](https://github.com/jlevy) and [@ThanosBaskous](https://github.com/ThanosBaskous),\n  but the content is the result of a community of contributors, editors, and experts.\n  Please help if you can. See the [contribution guidelines](CONTRIBUTING.md) for notes on roles and editorial process.\n\nfooter: |\n  Contributors are listed alphabetically with assigned roles first.\n  Please don't PR the AUTHORS.md or authors-info.yml files! It is auto-generated regularly by the project leads.\n  Please let the project leads know of any errors or omissions on this list.\n\nexclude:\n  gitter-badger\n  ReadmeCritic\n\nroles:\n  jlevy: project lead, editor (topics not otherwise assigned)\n  ThanosBaskous: project lead, editor (topics not otherwise assigned)\n  QuinnyPig: community lead, editor (news and updates, cost management)\n  max-zanko: editor (EC2, S3, Glacier, EMR, Redshift)\n  nitingithub: editor (cost management)\n  forwidur: editor (EBS, RDS)\n  lynnlangit: editor (IoT)\n  richadams: editor (VPC)\n  artemnikitin: editor (Certificate Manager)\n  bgdnlp: editor (EFS)\n  JCBarry: editor (CloudWatch)\n  nzoschke: editor (KMS)\n  lobster1234: editor (Batch, SQS, SNS)\n  donnemartin: expert (tools)\n  merrells: expert (cloud infrastructure, when to use AWS)\n  benkehoe: expert (IoT)\n  ehammond: expert (Lambda, serverless)\n  danhermann: expert (RDS)\n  kimschmidtsbrain: expert (AWS Marketplace, Aurora)\n  wumintendy: expert (ECS, CloudWatch, SQS, RDS, WAF)\n  lukedeo: expert (machine learning, Terraform, orchestration)\n  marcello3d:\n  golyshev:\n  Praveen Patnala:\n  kazuyukitanimura:\n  olawiberg:\n  weirded:\n  bittlingmayer:\n  rjpower:\n  alexanderatallah:\n  Jurgen Philippaerts:\n\ngroups:\n  - name: Leads\n    members:\n    - jlevy\n    - ThanosBaskous\n    - QuinnyPig\n  - name: Editors and Experts\n    members:\n    - max-zanko\n    - nitingithub\n    - forwidur\n    - lynnlangit\n    - richadams\n    - artemnikitin\n    - bgdnlp\n    - JCBarry\n    - nzoschke\n    - lobster1234\n    - donnemartin\n    - merrells\n    - benkehoe\n    - ehammond\n    - danhermann\n    - kimschmidtsbrain\n    - wumintendy\n    - lukedeo\n  - name: Contributors\n"
  },
  {
    "path": "admin/reformat-aggressive.sh",
    "content": "#!/bin/bash\n\n# Put main main Markdown files into canonical syntax (in place!) with markdownfmt.\n# XXX This is aggressive so we haven't been running. See also \n# https://github.com/shurcooL/markdownfmt/issues?utf8=%E2%9C%93&q=is%3Aopen%20author%3Ajlevy%20\n\nset -e -u -o pipefail\n\nhash markdownfmt >/dev/null 2>&1 || {\n  echo >&2 \"markdownfmt missing: Install https://github.com/shurcooL/markdownfmt and re-run\"\n  exit 1\n}\n\ncd $(dirname $0)/..\n\nmarkdownfmt -w README.md CONTRIBUTING.md\n"
  },
  {
    "path": "admin/reformat-gentle.sh",
    "content": "#!/bin/bash\n\n# Gently fix common Markdown formatting errors. Should be minimally invasive.\n\nset -e -u -o pipefail\n\nhash repren >/dev/null 2>&1 || {\n  echo >&2 \"repren missing: Install https://github.com/jlevy/repren and re-run\"\n  exit 1\n}\n\ncd $(dirname $0)/..\n\n# Extra spaces following a bullet replaced by tab per mkdownfmt convention.\n# Leave other stuff alone.\nrepren --from '^(\\s*)([-*])(\\s*  +\\s*)' --to '\\1\\2\\t' README.md CONTRIBUTING.md\n"
  },
  {
    "path": "translations/ru.md",
    "content": "![Открытое руководство](../figures/signpost-horiz1-1600.jpg)\n\nОткрытое руководство по Amazon Web Services\n=====================================\n\n[![Slack чат](https://img.shields.io/badge/Chat-Slack-ff69b4.svg \"Join us. Anyone is welcome!\")](http://slackhatesthe.cloud) ⇦ Присоединяйтесь к нам\n\n[Авторы](../AUTHORS.md) ∙ [Рекомендации по дополнению материала](../CONTRIBUTING.md)\n\nСодержание\n-----------------\n\n**Цель создания данного руководства**\n\n-\t[Почему открытое руководство?](#почему-открытое-руководство)\n-\t[Содержание](#содержание-1)\n-\t[Расшифровка обозначений](#расшифровка-обозначений)\n\n**Что такое AWS**\n\n-\t[Общая информация](#общая-информация)\n-\t[Обучение и карьерное развитие](#обучение-и-карьерное-развитие)\n-\t[Управление AWS](#управление-aws)\n-\t[Управление серверами и приложениями](#управление-серверами-и-приложениями)\n\n| Сервис AWS\t                        | Основные данные                | Советы                        | Известные ошибки и ограничения                                       |\n|---------------------------------------|--------------------------------|-------------------------------|------------------------------------------------|\n| [ALB](#alb) | [📗](#основы-alb) | [📘](#советы-по-alb) | [📙](#ошибки-и-ограничения-связанные-с-alb) |\n| [AMIs](#amis) | [📗](#основы-ami) | [📘](#советы-по-ami) | [📙](#ошибки-и-ограничения-связанные-с-ami) |\n| [API Gateway](#api-gateway) | [📗](#основы-api-gateway) | [📘](#советы-по-api-gateway) | [📙](#ошибки-и-ограничения-связанные-с-api-gateway) |\n| [Auto Scaling](#auto-scaling-автоматическое-масштабирование) | [📗](#основы-auto-scaling) | [📘](#советы-по-автоматическому-масштабированию) | [📙](#ошибки-и-ограничения-связанные-с-автоматическим-масштабированием) |\n| [Batch](#batch) | [📗](#основы-batch) | [📘](#советы-по-batch) |\n| [Certificate Manager](#менеджер-сертификатовcertificate-manager) | [📗](#основы-менеджера-сертификатов) | [📘](#советы-по-менеджеру-сертификатов) | [📙](#ошибки-и-ограничения-связанные-с-менеджером-сертификатов) |\n| [CLB (ELB)](#классический-балансировщик-нагрузкиclb) | [📗](#основы-clb) | [📘](#советы-по-clb) | [📙](#ошибки-и-ограничения-связанные-с-clb) |\n| [CloudFront](#cloudfront) | [📗](#основы-cloudfront) | [📘](#советы-по-cloudfront) | [📙](#ошибки-и-ограничения-связанные-с-cloudfront) |\n| [CloudFormation](#cloudformation) | [📗](#основы-cloudformation) | [📘](#советы-по-cloudformation) | [📙](#ошибки-и-ограничения-связанные-с-cloudformation) |\n| [CloudWatch](#cloudwatch) | [📗](#основы-cloudwatch) | [📘](#советы-по-cloudwatch) | [📙](#ошибки-и-ограничения-связанные-с-cloudwatch) |\n| [Device Farm](#device-farm) | [📗](#основы-device-farm) | [📘](#советы-по-device-farm) | [📙](#ошибки-и-ограничения-связанные-с-device-farm) |\n| [DirectConnect](#directconnect) | [📗](#основы-directconnect) | [📘](#советы-по-directconnect) |  |\n| [DynamoDB](#dynamodb) | [📗](#основы-dynamodb) | [📘](#советы-по-dynamodb) | [📙](#ошибки-и-ограничения-связанные-с-dynamodb) |\n| [EBS](#ebs) | [📗](#основы-ebs) | [📘](#советы-по-ebs) | [📙](#ошибки-и-ограничения-связанные-с-ebs) |\n| [EC2](#ec2) | [📗](#основы-ec2) | [📘](#советы-по-ec2) | [📙](#ошибки-и-ограничения-ec2) |\n| [ECS](#ecs) | [📗](#основы-ecs) | [📘](#советы-по-ecs) |  |\n| [EKS](#eks) | [📗](#основы-eks) | [📘](#советы-по-eks) | [📙](#ошибки-и-ограничения-связанные-с-eks)  |\n| [EFS](#efs) | [📗](#основы-efs) | [📘](#советы-по-efs) | [📙](#ошибки-и-ограничения-связанные-с-efs) |\n| [Elastic Beanstalk](#elastic-beanstalk) | [📗](#основы-elastic-beanstalk) | [📘](#советы-по-elastic-beanstalk) | [📙](#ошибки-и-ограничения-связанные-с-elastic-beanstalk) |\n| [Elastic IPs](#elastic-ips) | [📗](#основы-elastic-ip) | [📘](#советы-по-elastic-ip) | [📙](#ошибки-и-ограничения-связанные-с-elastic-ip) |\n| [ElastiCache](#elasticache) | [📗](#основы-elasticache) | [📘](#советы-по-elasticache) | [📙](#ошибки-и-ограничения-связанные-с-elasticache) |\n| [EMR](#emr) | [📗](#основы-emr) | [📘](#советы-по-emr) | [📙](#ошибки-и-ограничения-связанные-с-emr) |\n| [Fargate](#fargate) | [📗](#основы-fargate) | [📘](#советы-по-fargate) | [📙](#ошибки-и-ограничения-связанные-с-fargate) |\n| [Glacier](#glacier) | [📗](#основы-glacier) | [📘](#советы-по-glacier) | [📙](#ошибки-и-ограничения-связанные-с-glacier) |\n| [IoT](#iot) | [📗](##основы-iot) | [📘](#советы-по-iot) | [📙](#ошибки-и-ограничения-связанные-с-iot) |\n| [Kinesis Firehose](#kinesis-firehose) |  |  | [📙](#ошибки-и-ограничения-связанные-с--kinesis-firehose) |\n| [Kinesis Streams](#kinesis-streams) | [📗](#основы-kinesis-streams) | [📘](#советы-по-kinesis-streams) | [📙](#ошибки-и-ограничения-связанные-с-kinesis-streams) |\n| [KMS](#kms) | [📗](#основы-kms) | [📘](#советы-по-kms) | [📙](#ошибки-и-ограничения-связанные-с-kms) |\n| [Lambda](#lambda) | [📗](#основы-lambda) | [📘](#советы-по-lambda) | [📙](#ошибки-и-ограничения-связанные-с-lambda) |\n| [Load Balancers](#балансировщики-нагрузкиload-balancers) | [📗](#основы-load-balancer) | [📘](#советы-по-load-balancer) | [📙](#ошибки-и-ограничения-связанные-с-load-balancer) |\n| [Mobile Hub](#mobile-hub) | [📗](#основы-mobile-hub) | [📘](#советы-по-mobile-hub) | [📙](#ошибки-и-ограничения-связанные-с-mobile-hub) |\n| [OpsWorks](#opsworks) | [📗](#основы-opsworks) | [📘](#советы-по-opsworks) | [📙](#ошибки-и-ограничения-связанные-с-opsworks) |\n| [RDS](#rds) | [📗](#основы-rds) | [📘](#советы-по-rds) | [📙](#ошибки-и-ограничения-связанные-с-rds) |\n| [RDS Aurora](#rds-aurora) | [📗](#основы-rds-aurora) | [📘](#rds-aurora-tips) | [📙](#rds-aurora-gotchas-and-limitations) |\n| [RDS Aurora MySQL](#rds-aurora-mysql) | [📗](##основы-rds-aurora-mysql) | [📘](#советы-по-rds-aurora-mysql) | [📙](#ошибки-и-ограничения-связанные-с--rds-aurora-mysql) |\n| [RDS Aurora PostgreSQL](#rds-aurora-postgresql) | [📗](#основы-rds-aurora-postgresql) | [📘](#советы-по-rds-aurora-postgresql) | [📙](#ошибки-и-ограничения-связанные-с-rds-aurora-postgresql) |\n| [RDS MySQL и MariaDB](#rds-mysql-и-mariadb) | [📗](#основы-rds-mysql-и-mariadb) | [📘](#советы-по-rds-mysql-и-mariadb) | [📙](#ошибки-и-ограничения-связанные-с--rds-mysql-и-mariadb) |\n| [RDS PostgreSQL](#rds-postgresql) | [📗](#основы-rds-postgresql) | [📘](#советы-по-rds-postgresql) | [📙](#ошибки-и-ограничения-связанные-с--rds-postgresql) |\n| [RDS SQL Server](#rds-sql-server) | [📗](#основы-rds-sql-server) | [📘](#советы-по-rds-sql-server) | [📙](#ошибки-и-ограничения-связанные-с--rds-sql-server) |\n| [Redshift](#redshift) | [📗](#основы-redshift) | [📘](#советы-по-redshift) | [📙](#ошибки-и-ограничения-связанные-с-redshift) |\n| [Route 53](#route-53) | [📗](#основы-route-53) | [📘](#советы-по-route-53) | [📙](#ошибки-и-ограничения-связанные-с-route-53) |\n| [S3](#s3) | [📗](#основы-s3) | [📘](#советы-по-s3) | [📙](#ошибки-и-ограничения-s3) |\n| [Безопасность и IAM](#безопасность-и-iam) | [📗](#основы-безопасности-и-iam) | [📘](#советы-по-безопасности-и-iam) | [📙](#ошибки-и-ограничения-в-вопросе-обеспечения-безопасности-и-iam) |\n| [SES](#ses) | [📗](#основы-ses) | [📘](#советы-по-ses) | [📙](#ошибки-и-ограничения-связанные-с-ses) |\n| [SNS](#sns) | [📗](#основы-sns) | [📘](#советы-по-sns) | [📙](#ошибки-и-ограничения-связанные-с-sns) |\n| [SQS](#sqs) | [📗](#основы-sqs) | [📘](#советы-по-sqs) | [📙](#ошибки-и-ограничения-связанные-с-sqs) |\n| [Step Functions](#step-functions) | [📗](#основы-step-functions) | [📘](#советы-по-step-function) | [📙](#ошибки-и-ограничения-связанные-с-step-functions) |\n| [WAF](#waf) | [📗](#основы-waf) | [📘](#советы-по-waf) | [📙](#ошибки-и-ограничения-связанные-с-waf) |\n| [VPC, Сетевая безопасность и Группы безопасности](#vpc-сетевая-безопасность-и-группы-безопасности) | [📗](#основы-vpc) | [📘](#советы-по-vpc-и-сетевой-безопасности) | [📙](#ошибки-и-ограничения-связанные-с-vpc-и-сетевой-безопасностью) |\n\n**Особые темы**\n\n-\t[Высокая доступность](#высокая-доступность)\n-\t[Платежи и управление расходами](#платежи-и-управление-расходами)\n-\t[Дополнительные материалы](#дополнительные-материалы)\n\n**Правовая информация**\n\n-\t[Отказ от ответственности](#отказ-от-ответственности)\n-\t[Информация о лицензии](#информация-о-лицензии)\n\n**Диаграммы и таблицы**\n\n[![Инструменты и услуги, представленные на рынке](../figures/aws-market-landscape-320px.png)](#инструменты-и-услуги-представленные-на-рынке) [![Стоимость передачи данных при работе с AWS](../figures/aws-data-transfer-costs-320px.png)](#aws-data-transfer-costs)\n\n-\t[Инфографика: Инструменты и услуги, представленные на рынке](#инструменты-и-услуги-представленные-на-рынке): Выборка сторонних компаний/продуктов\n-\t[Инфографика: Стоимость передачи данных при работе с AWS](#затраты-на-передачу-данных-в-aws): Визуальный обзор расходов на передачу данных\n-\t[Таблица: Матрица сервисов](#матрица-сервисов): Сравнение сервисов AWS с альтернативными вариантами\n-\t[Таблица: Зрелось продуктов AWS и выпуски](#зрелость-продуктов-aws-и-выпуски): Релизы продуктов AWS \n-\t[Таблица: Долговечность и надежность хранения, доступность и цена](#долговечность-и-надежность-хранения-доступность-и-цена): Количественное сравнение\n\nПочему открытое руководство?\n------------------\n\nМножество информации об AWS уже написано. Большинство изучает AWS читая блоги или “[руководство по началу работы](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html)” и ссылаясь на [официальную документацию AWS](https://aws.amazon.com/documentation/). Тем не менее, поиск достоверной и, связанной с практическим использованием, информации  не так то прост. Официальная документация AWS является прекрасным, но очень обширным ресурсом, который мало кто читает полностью, по причине отсутствия времени, кроме того, он не содержит ничего, кроме официальных фактов и не учитывает опыт практикующих инженеров. Информация в блогах или на [Stack Overflow](http://stackoverflow.com/questions/tagged/amazon-web-services) также не всегда актуальна.\n\nЭто руководство создано инженерами для инженеров использующих AWS. Мы поставили цель создать полезный, актуальный спсравочник, который объединяет ссылки, советы, рекомендации и лучшие практики. Идея создания данного руководства возникла в ходе обсуждений под пиво у [нескольких инженеров](../AUTHORS.md) которые широко применяли AWS в своей практике.\n\nПеред использованием данного руководства, пожалуйста прочтите [**информацию о лицензии**](#информация-о-лицензии) и [**отказ от ответственности**](#отказ-от-ответственности).\n\n### Помоги, пожалуйста!\n\n**Это ранняя черновая версия** Это наша первая попытка собрать и скомпоновать информацию, поэтому она еще далеко не исчерпывающая и может содержать пропуски или ошибки. \n\n[![Slack чат](https://img.shields.io/badge/Chat-Slack-ff69b4.svg \"Join us. Anyone is welcome!\")](https://join.slack.com/t/og-aws/shared_invite/enQtODM2NjY1NDQ2MTgxLWYwY2VjZDBiOGU1YTJjOWUwNTY3NjEyODA0NzY1N2MxNjhhZmYwZTU0NjNhMjNlNGVjODdlNTI4N2Y1YWIwNGE)\n\nТы можешь помочь [**присоединившись к Slack чату**](https://join.slack.com/t/og-aws/shared_invite/enQtODM2NjY1NDQ2MTgxLWYwY2VjZDBiOGU1YTJjOWUwNTY3NjEyODA0NzY1N2MxNjhhZmYwZTU0NjNhMjNlNGVjODdlNTI4N2Y1YWIwNGE) (мы любим общаться об AWS в общем и целом, даже если тебе нечего сообщить и ты хочешь спросить - обсуждения помогают сообществу и этому руководству развиваться) и [**внося дополнения к данному руководству**](CONTRIBUTING.md). Это руководство *открыто для дополнения*, в отличии от блога, оно может продолжать развиваться. Как и в любом open source проекте, мы объединяем усилия и проверяем информацию, чтобы быть уверенными в высоком качестве информации.\n\nСодержание\n-----\n\n-\tНа текущий момент это руководство охватывает отдельные “основные(core)” сервисы AWS, такие как EC2, S3, Балансировщики нагрузки, EBS и IAM, а также некоторые подробности и советы при работе с остальными сервисами. Мы ожидаем, что с течением времени охват расширится.\n-\tЭто не пошаговое руководство, а скорее коллекция различной информации, которую вы можете прочитать и возвращаться к ней в при необходимости. Информация будет полезна, как начинающим, так и опытным инженерам.\n-\tМы хотим, чтобы это руководство было:\n\t-\t**Кратким:** Старайтесь излагать информацию компактно и используйте ссылки\n\t-\t**Практическим:** Основные факты, конкретные детали, советы, отловленные ошибки и прочие “общественные знания”\n\t-\t**Актуальным:** Мы можем регулярно обновлять его, и каждый может внести посильный вклад в улучшение\n\t-\t**Заставляющим задуматься:** Цель данного руководства - быть полезным, нежели просто изложить сухие факты. Мнение с рациональным зерном всегда приветствуется. Предложения, заметки и мнения, основанные на реальном опыте работы с AWS могут быть чрезвычайно ценными. (Мы верим, что это возможно с помощью руководства подобного формата, в отличии от некоторых [других мест](http://meta.stackexchange.com/questions/201994/is-there-a-place-to-ask-opinion-based-questions).)\n-\tЭто руководство не было проспонсировано ни AWS, ни связанным с AWS вендорами. Оно написано инженерами для инженеров, которые используют AWS в своей работе.\n\nРасшифровка обозначений\n------\n\n-\t📒 Обозначает официальную документацию и страницы AWS\n-\t🔹 Важный или часто пропускаемый совет\n-\t❗ “Серьезная” ошибка (используется в тех случаях, когда риски, затраты времени или ресурсов значительны: критические риски безопасности, ошибки, грозящие значительными финансовыми затратами или плохие архитектурные решения, которые принципиально сложно исправить)\n-\t🔸 “Обычная” ошибка, ограничение, или странность (используется в тех случаях, когда ошибка вызывает неработоспособность, поломку или когда масштабирование происходит некорректно)\n-\t📜 Недокументированная особенность(фича) (народная информация)\n-\t🐥 Относительно новые (и, возможно, незрелые) сервисы и особенности(фичи)\n-\t⏱ Обсуждение производительности\n-\t⛓ Привязка: Продукты или решения, которые скорее всего привяжут вас к AWS таким образом, что переход на не-AWS альтернативу будет дорогостоящим с точки зрения инженерных усилий.\n-\t🚪 Альтернативные не-AWS варианты\n-\t💸 Вопросы стоимости, обсуждения и проблемы\n-\t🕍 Мягкое предупреждение, связанное с тем, что “универсальное решение” или модный фреймворк могут потребовать значительного времени, чтобы разобраться и понять, как это работает, при этом результат может не соответствовать потребностям в точности; в отличии от точечного решения(собор(иконка) является отсылкой к [Метафоре Рэймонда](https://en.wikipedia.org/wiki/The_Cathedral_and_the_Bazaar)\\)\n-\t📗📘📙 Цвета обозначают основы, советы, отловленные ошибки соответственно.\n-\t🚧 Области где требуется исправление или улучшение (возможно с ссылкой на проблему, если можете — помогите!)\n\nОбщая информация\n-------------------\n\n### Когда использовать AWS\n\n-\t[AWS](https://en.wikipedia.org/wiki/Amazon_Web_Services) - доминирующий на мировом рынке провайдер облачных услуг.\n\t-\tВ общем и целом, “[облачные вычисления](https://en.wikipedia.org/wiki/Cloud_computing)” могут относиться к одному из трех типов облака: “публичное,” “частное,” и/или “гибридное.” AWS является провайдером публичных облачных сред, таким образом, каждый может их использовать. Частные облака обычно разворачиваются внутри одной (обычно большой) организации. Множество компаний по всему миру использует так называемый гибрид частного и публичного облака.\n\t-\tОсновными сервисами, предоставляемыми AWS являются [инфраструктура как сервис](https://en.wikipedia.org/wiki/Cloud_computing#Infrastructure_as_a_service_.28IaaS.29) (IaaS) — то есть виртуальные машины и сопутствующая инфраструктура. Другие модели облачных сервисов включают в себя [платформу как сервис](https://en.wikipedia.org/wiki/Cloud_computing#Platform_as_a_service_.28PaaS.29) (PaaS), которая представляет из себя платформу для развертывания клиентских приложений без оглядки на инфраструктуру, а также [программное обеспечение как сервис](https://en.wikipedia.org/wiki/Cloud_computing#Software_as_a_service_.28SaaS.29) (SaaS), котороая представляет из себя облачные приложения. Кроме того, AWS предлагает новые модели облачных сервисов.\n\t-\tС точки зрения бизнеса, при использовании инфраструктуры, как сервис, вы получаете новую парадигму — это [операционные расходы(OpEx), а не капитальные расходы(CapEx)](http://www.investopedia.com/ask/answers/020915/what-difference-between-capex-and-opex.asp) (за исключением случаев [забронированной инфраструктуры(Reserved Instances)](https://aws.amazon.com/ec2/purchasing-options/reserved-instances/), которая в таком случае является капитальным расходом(CapEx).\n-\tДоход AWS за 12 месяцев составил [**$32.5 миллиарда долларов США**](https://ir.aboutamazon.com/static-files/ca9f2d27-46e7-4006-86f1-0c6ccb026a04) по данным на третитй квартал 2019 года, исходя из официальных данных или примерно **12%** от всего дохода Amazon.com за тот же период.\n-\t**Главные причины использовать AWS:**\n\t-\tЕсли ваша компания создает системы и/или продукты, которым необходимо масштабирование\n\t-\tи у вас есть технические ноу-хау\n\t-\tи вы хотите использовать наиболее гибкие инструменты\n\t-\tи вы еще не сильно привязаны к какой-либо иной инфраструктуре\n\t-\tи у вас нет каких-либо внутренних, регуляторных или нормативных причин, по которым вы не можете использовать публичное облачное решение\n\t-\tи вы не завязаны на решения только от Microsoft :)\n\t-\tи у вас нет явных причин использовать именно Google Cloud\n\t-\tи вы можете себе позволить, дискутировать или договариваться о больших или меньших затратах\n\t-\t... тогда, судя по всему, AWS это неплохой вариант для рассмотрения.\n-\tКаждая из вышеперечисленных причин может указывать на ситуации, когда другие услуги предпочтительнее. На практике многие, если не большинство, технические стартапы, а также ряд современных крупных компаний могут или уже получают выгоду от использования AWS. Многие крупные предприятия частично переносят внутреннюю инфраструктуру на Azure, Google Cloud и AWS.\n-\t**Расходы:** Оплата и управление расходами настолько большие темы, что у нас есть [отдельный раздел на эту тему](#платежи-и-управление-расходами).\n-\t🔹**EC2 и другие сервисы:** Большинство пользователей AWS наиболее знакомы с [EC2](#ec2), флагманским продуктом AWS - виртуальными серверами, и возможно некоторыми другими, такими как S3 и CLB(классическими балансировщиками нагрузки). Однако продукты AWS на текущий момент выходят далеко за рамки классической модели IaaS и зачастую компании не всегда понимают или видят ценность в использовании многочисленных продуктов AWS ввиду [быстрого роста](#какие-сервисы-использовать) количества сервисов, их новизны и сложности, путаницы с названиями, и боязни ⛓привязки к проприетарным технологиям AWS. И, хотя все вышеперечисленное может звучать устрашающе, крайне важно для лиц, принимающих технические решения в компании, понимать всю широту услуг предоставляемых AWS и принимать обоснованные решения. (Мы надеемся, что данное руководство поможет в этом.)\n-\t🚪**AWS и другие облачные провайдеры:** В то время, как AWS является ведущим IaaS провайдером (31% рынка исходя [из оценки рынка за 2016 год](https://www.srgresearch.com/articles/aws-remains-dominant-despite-microsoft-and-google-growth-surges)), существует значительная конкуренция на рынке и альтернативные решения, которые больше подходят некоторым компаниям. [Этот отчет от Gartner](https://www.gartner.com/doc/reprints?id=1-2G2O5FC&ct=150519&st=sb) содержит хороший обзор основных игроков на рынке облачных услуг:\n\t-\t[**Google Cloud Platform**](https://cloud.google.com/). GCP пришел на рынок позже AWS, но обладает обширными ресурсами и на текущий момент используется многими компаниями, в том числе некоторыми крупными корпорациями. GCP постепенно занимает свою нишу на рынке. Не все сервисы AWS имеют аналоги в GCP. И наоборот: В частности, GCP предлагает некоторые более продвинутые, основанные на машинном обучении, сервисы, такие как [Vision](https://cloud.google.com/vision/), [Speech](https://cloud.google.com/speech/), и [Natural Language](https://cloud.google.com/natural-language/) APIs. Обычно это не является распространенной практикой, когда действующий проект запущенный на одной платформе переключается на другую, однако такое случается: [Spotify мигрировал](http://www.wsj.com/articles/google-cloud-lures-amazon-web-services-customer-spotify-1456270951) с AWS на Google Cloud. Обсуждение сравнительных выгод можно найти [на Quora](https://www.quora.com/What-are-the-reasons-to-choose-AWS-over-Google-Cloud-or-vice-versa-for-a-high-traffic-web-application). Особо следует отметить тот факт, что VPC в GCP [глобальны по умолчанию](https://cloud.google.com/vpc/) с подсетями в регионах, в то время как VPC в AWS располагаются в строго определенном регионе. Это дает преимущество GCP в том случае, если вы изначально проектируете приложения с распределенной гео-репликацией. Также возможно [совместное использование одного VPC в GCP](https://cloud.google.com/compute/docs/shared-vpc/) между несколькими проектами (что примерно аналогично разным AWS аккаунтам), в то время, как в AWS вы должны их обеспечить их соединение. Также возможно [связать VPC в GCP](https://cloud.google.com/compute/docs/vpc/vpc-peering) таким же способом, как это сделано в AWS.\n\t-\t[**Microsoft Azure**](https://azure.microsoft.com/en) де-факто является выбором компаний и команд, ориентированных на стек технологий Microsoft, кроме того Azure уделяет огромное внимание технологиям Linux.\n\t-\tВ **Китае**, доля AWS относительно мала. На рынке доминирует [Alibaba Cloud](https://www.alibabacloud.com/), ранее именовавшийся [Aliyun](https://intl.aliyun.com/).\n\t-\tОтдельные очень крупные компании могут в свою очередь пожелать сократить расходы путем перехода на собственную инфраструктуру. Например, [Dropbox мигрировал](https://news.ycombinator.com/item?id=11282948) на собственную инфраструктуру.\n\t-\tДругие облачные провайдеры, такие как [Digital Ocean](https://www.digitalocean.com/) предлагают похожие сервисы, иногда значительно более простые в использовании, более клиенто-ориентированную поддержку или более низкие цены. В любом случае, ни один из них не соответствует AWS по широте ассортимента, доминации на рынке, осведомленности клиентов о компании и продуктах.\n\t-\tТрадиционные хостинг провайдеры, такие как [Rackspace](https://www.rackspace.com/) также предлагают облачные решения.\n-\t🚪**AWS и PaaS:** Если ваша цель запустить простой сервис, которые делает что-то относительно простое и вы хотите минимизировать трудозатраты на обслуживание инфраструктуры, рассмотрите как вариант развертывания [платформу-как-сервис](https://en.wikipedia.org/wiki/Platform_as_a_service) такую как [Heroku](https://www.heroku.com/). Подход AWS к PaaS модели, как например, Elastic Beanstalk, возможно слишком сложен, в особенности для простых случаев использования.\n-\t🚪**AWS и Web-хостинг:** Если ваша главная цель - разместить веб-сайт или блог и вы не собираетесь создавать веб-приложение или какой-либо сложные сервис, возможно вам стоит рассмотреть размещение на площадке одного из мириадов [хостинг провайдеров](https://www.google.com/search?q=web+hosting).\n-\t🚪**AWS vs. managed hosting:** Традиционно многие компании платят провайдерам [управляемого хостинга](https://en.wikipedia.org/wiki/Dedicated_hosting_service),чтобы те обслуживали оборудование в своих ЦОД для них, а затем создают и развертывают программное обеспечение на базе арендованного физического оборудования. Это имеет смысл для тех предприятий, которые хотят иметь возможность прямого контроля аппаратного обеспечения, по причине развертывания легаси систем, а также в целях обеспечения необходимой производительности или в целях соответствия определенным ограничениям и правилам, в то же время технологические компании и ИТ-стартапы считают такой вариант размещения старомодным и не нужным.\n-\t**Сложность:** AWS позволит вам строить и масштабировать системы до размеров крупнейших компаний, однако сложность сервисов при использовании в таких масштабах требует значителнього уровня знаний и опыта. Даже для очень простых случаев использования может потребоваться значительно больше знаний, чтобы сделать все “правильно” в AWS, нежели в более простой среде, как например Heroku или Digital Ocean. (Это руководство может помочь!)\n-\t**Географическое местоположение:** AWS имеет центры обработки данных в [в более чем дюжине географических местоположений](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions), известных как **регионы(regions)**, в Европе, Восточной Азии, Северной и Южной Америке, а теперь и в Австралии и Индии. Также имеется значительно большее количество **точек доступа(edge locations)** по всему миру для снижения задержек при доступе к сервисам, например CloudFront.\n\t-\tПосмотрите [текущий список](https://aws.amazon.com/about-aws/global-infrastructure/) регионов и точек доступа, включающий в том числе и планируемые.\n\t-\tЕсли ваша инфраструктура должна располагаться в определенной физической близости к другим сервисам по причине определенной зависимости от задержек или пропускной способности (например, задержка до рекламного обменника), возможность использования AWS может зависеть от местоположения. \n-\t⛓**Привязка:** Так как вы используете AWS, важно понимать, когда вы используете сервисы AWS, которые не имеют эквивалентных аналогов где-либо.\n\t-\tПривязка может быть вполне приемлимой для вашей компании или может стать значительным риском. Крайне важно с точки зрения бизнеса сделать осознанный выбор, учитывая стоимость, эксплуатационные качества, непрерывность бизнеса, и конкурентные риски связанные с привязкой к AWS. С другой стороны AWS настолько доминирующий и надежный вендор, что многие компании используют AWS в полной мере. Однако, некоторые могут рассказывать истории об [опасностях “облачной тюрьмы” когда издержки возрастают](http://firstround.com/review/the-three-infrastructure-mistakes-your-company-must-not-make/).\n\t-\tКак правило, чем больше сервисов AWS вы используете, тем больше ваша привязка к AWS — то есть, больше технических ресурсов (времени и денег) потребуется для перехода к другому провайдеру в будущем.\n\t-\tОсновные сервисы, такие как виртуальные сервера и стандартные базы данных, обычно довольно таки легко перенести на других провайдеров или в локальный дата-центр. Другие же, такие как балансировщики нагрузки и IAM, являются специфичными в AWS, однако имеются похожие эквивалетные сервисы предлагаемые другими провайдерами. Ключевым моментом, который необходимо учитывать, является вопрос, проектируют ли инженера системы на основе конкретных сервисов AWS, которые не являются открытыми, или же на основе взаимозаменяемых сервисов. Например, Lambda, API Gateway, Kinesis, Redshift, и DynamoDB не имеют похожих эквивалентов, как коммерческих, так и открытых, в то время как  EC2, RDS (MySQL или Postgres), EMR, и ElastiCache более или менее имеют. (Более подробно [тут](#какие-сервисы-использовать), где такие сервисы помечены значком ⛓.)\n-\t**Использование AWS с другими облачными провайдерами:** Многие пользователи объединяют использование AWS с другими не-AWS сервисами. Например, легаси системы или критичные к раскрытию данных могут находиться на арендованном у хостинг провайдера оборудовании, в то время, как остальные системы находятся в AWS. Или компания может использовать S3, а у другого провайдера находятся системы, которые делают все остальное. Как бы там не было, маленькие стартапы или проекты, начинающиеся с нуля, обычно используют только AWS или Google Cloud.\n-\t**Гибридные облака:** На крупных предприятиях обычно используется так называемое [гибридное развертывание](https://aws.amazon.com/enterprise/hybrid/) включающее в себя частное облако или локальные сервера и AWS — или другие корпоративные облачные провайдеры, такие как [IBM](https://www.ibm.com/it-infrastructure/us-en/hybrid-cloud/)/[Bluemix](http://www.ibm.com/cloud-computing/bluemix/hybrid/), [Microsoft](https://www.microsoft.com/en-us/cloud-platform/hybrid-cloud)/[Azure](https://azure.microsoft.com/en-us/overview/azure-stack/), [NetApp](http://www.netapp.com/us/solutions/cloud/hybrid-cloud/), or [EMC](http://www.emc.com/en-us/cloud/hybrid-cloud-computing/index.htm).\n-\t**Основные клиенты:** Кто использует AWS и Google Cloud?\n\t-\t[Список клиентов AWS](https://aws.amazon.com/solutions/case-studies/) включает в себя большое количество мейнстримных онлайн бизнесов и крупных брендов, таких как Netflix, Pinterest, Spotify (переезжает на Google Cloud), Airbnb, Expedia, Yelp, Zynga, Comcast, Nokia, и Bristol-Myers Squibb.\n\t-\t[Список клиентов Azure](https://azure.microsoft.com/en-us/case-studies/) включает в себя такие компании, как NBC Universal, 3M и Honeywell Inc.\n\t-\t[Список клиентов Google Cloud](https://cloud.google.com/customers/) также довольно таки большой и включает в себя несколько мэйнстриных сайтов, таких как [Snapchat](http://www.businessinsider.com/snapchat-is-built-on-googles-cloud-2014-1), Best Buy, Domino’s, и Sony Music.\n\n### Какие сервисы использовать\n\n-\tAWS предлагает *множество* различных сервисов — [около сотни](https://aws.amazon.com/products/) на момент последнего подсчета.\n-\tБольшинство клиентов интенсивно использует некоторое количество сервисов, некоторое количество не настолько интенсивно и не использует остальные вообще. Какие сервисы вы будете использовать - полностью зависит от конкретного случая использования. Выбор варьируется от компании к компании.\n-\t**Незрелые и непопулярные сервисы:** Только от того, что AWS звучит, как многообещающий сервис, это вовсе не означает, что вы должны его использовать. Некоторые сервисы имеют довольно-таки узкую область применения, некоторые незрелые или сильно навороченные, или имеют ограничения, так что создание собственного решения может быть лучше. Мы попытаемся дать вам понимание, путем разбиения сервисов по категориям.\n-\t**Инфраструктура, которую необходимо знать:** В большинстве своем обычные малые и средние компании сосредоточатся в первую очередь на следующих сервисах. Если вы управляете использованием ресурсов в AWS, вы должны хотя бы немного во всем этом разбираться. (Даже если вы их не используете, вам следует изучить их достаточно для того, чтобы сделать осознанный выбор)\n\t-\t[IAM](#безопасность-и-iam): Пользовательские учетные записи и доступы(Вам следует подумать об учетных записях и доступа на самой ранней стадии!)\n\t-\t[EC2](#ec2): Виртуальные сервера и сопутствующие компоненты, включая:\n\t\t-\t[AMIs](#amis): Образы виртуальных машин\n\t\t-\t[Load Balancers](#балансировщики-нагрузкиload-balancers): CLBs и ALBs\n\t\t-\t[Autoscaling](#auto-scaling-автоматическое-масштабирование): Масштабирование емкости(добавление и удаление серверов в зависимости от нагрузки)\n\t\t-\t[EBS](#ebs): Сетевые диски\n\t\t-\t[Elastic IPs](#elastic-ips): Назначаемые IP адреса\n\t-\t[S3](#s3): Хранилище файлов\n\t-\t[Route 53](#route-53): DNS и регистрация доменов\n\t-\t[VPC](#vpc-сетевая-безопасность-и-группы-безопасности): Виртуальные сети, безопасность в сети, и ко-локейшн; используется автоматически\n\t-\t[CloudFront](#cloudfront): CDN для размещения контента\n\t-\t[CloudWatch](#cloudwatch): Оповещения, уведомления, мониторинг\n-\t**Управляемые сервисы:** Существующие программные решения, которые вы можете развернуть сами, но таким образом, что они управляются AWS:\n\t-\t[RDS](#rds): Управляемая реляционная база данных (управляемые базы данных MySQL, Postgres, и разработка Amazon - Aurora )\n\t-\t[EMR](#emr): Управляемый Hadoop\n\t-\t[Elasticsearch](https://aws.amazon.com/elasticsearch-service/): Управляемый Elasticsearch\n\t-\t[ElastiCache](https://aws.amazon.com/elasticache/): Управляемый Redis и Memcached\n-\t**Опциональная, но важная инфраструктура:** Эти ключевые и полезные инфраструктурные компоненты менее широко известны и реже используются. У вас могут быть вполне обоснованные причины использовать альтернативные варианты, поэтому необходимо крайне аккуратно оценить, удовлетворяют ли данные сервисы ваши потребности:\n\t-\t⛓[Lambda](#lambda): Выполнение небольших, полностью управляемых задач, так называемая “serverless” технология\n\t-\t[CloudTrail](https://aws.amazon.com/cloudtrail/): Логирование и аудит AWS API вызовов (важно, но часто игнорируется)\n\t-\t⛓🕍[CloudFormation](#cloudformation): Шаблонная конфигурация коллекций ресурсов AWS\n\t-\t🕍[Elastic Beanstalk](https://aws.amazon.com/elasticbeanstalk/): Полностью управляемая платформа (PaaS) для развертывания упакованных приложений на языках Java, .NET, PHP, Node.js, Python, Ruby, Go, и Docker\n\t-\t🐥[EFS](#efs): Сетевая файловая система совместимая с NFSv4.1\n\t-\t⛓🕍[ECS](#ecs): Управление Docker контейнерами/кластерами (к слову, Docker также может быть запущен в других сервисах, без использования ECS)\n\t-   🕍 [EKS](#eks): Управление Docker контейнерами/кластерами на основе оркестратора Kubernetes (K8)\n\t-\t⛓[ECR](https://aws.amazon.com/ecr/): Приватные реестр Docker образов\n\t-\t🐥[Config](https://aws.amazon.com/config/): Инвентаризация ресурсов AWS, история изменений, оповещения об изменениях\n\t-\t🐥[X-Ray](https://aws.amazon.com/xray/): Анализ трейсов и отладка для распределенных приложений, таких как микросервисы\n-\t**Специализированная инфраструктура:** Эти услуги ориентированы на конкретные случаи применения, таким образом необходимо произвести оценку, подходят ли они в вашей ситуации. Многие из них также имеют проприетарную архитектуру, таким образом привязывая вас к AWS. \n\t-\t⛓[DynamoDB](#dynamodb): NoSQL хранилище ключ-значение с низкими задержками\n\t-\t⛓[Glacier](#glacier): Медленная и дешевая альтернатива S3\n\t-\t⛓[Kinesis](https://aws.amazon.com/kinesis/): Потоковый сервис(распределенные логи)\n\t-\t⛓[SQS](https://aws.amazon.com/sqs/): Сервис очереди сообщений\n\t-\t⛓[Redshift](#redshift): Хранилище данных\n\t-\t🐥[QuickSight](https://aws.amazon.com/quicksight/): Сервис бизнес-аналитики\n\t-\t[SES](https://aws.amazon.com/ses/): Отправляйте или принимайте сообщения в целях маркетинга или транзакций\n\t-\t⛓[API Gateway](https://aws.amazon.com/api-gateway/): Проксирование, управление и обеспечение безопасности вызовов API\n\t-\t⛓[IoT](#iot): Управление двунаправленной связью через HTTP, WebSockets и MQTT между AWS и клиентами (часто, но не обязательно такими “вещами”, как устройства или датчики)\n\t-\t⛓[WAF](https://aws.amazon.com/waf/): Интернет ориентированный межсетевой экран использующийся CloudFront для отражения атак\n\t-\t⛓[KMS](#kms): Безопасное хранение и управление ключами шифрования\n\t-\t[Inspector](https://aws.amazon.com/inspector/): Аудит безопасности\n\t-\t[Trusted Advisor](https://aws.amazon.com/premiumsupport/trustedadvisor/): Автоматические советы по снижению издержек или внесению улучшений\n\t-\t🐥[Certificate Manager](https://aws.amazon.com/certificate-manager/): Управление SSL/TLS сертификатами для сервисов AWS\n\t-\t🐥⛓[Fargate](https://aws.amazon.com/fargate/): Управление Docker контейнерами, бэкенд для ECS и EKS\n-\t**Комплексные сервисы:** Они также специфичны, но являются полноценными услугами, которые призваны решить сложные проблемы, однако могут привязать к себе. Полезность зависит от ваших требований. Если у вас есть большие или значительные потребности, возможно это может быть решено на уровне внутренних систем и инженерных команд. \n\t-\t[Machine Learning](https://aws.amazon.com/machine-learning/): Классификация и модели машинного обучения\n\t-\t[Lex](https://aws.amazon.com/lex/): Автоматическое распознавание речи (ASR) и понимание языка (NLU)\n\t-\t[Polly](https://aws.amazon.com/polly/): Движок перевода текста в речь в облаке\n\t-\t[Rekognition](https://aws.amazon.com/rekognition/): Сервис распознавания изображений\n\t-\t⛓🕍[Data Pipeline](https://aws.amazon.com/datapipeline/): Управляемый сервис трансформации данных\n\t-\t⛓🕍[SWF](https://aws.amazon.com/swf/): Управляемый менеджер состояний для распределенного рабочего потока(workflow)\n\t-\t⛓🕍[Lumberyard](https://aws.amazon.com/lumberyard/): 3D игровой движок\n-\t**Разработка приложений/мобильных приложений:**\n\t-\t[SNS](https://aws.amazon.com/sns/): Управление push уведомлениями и другими уведомлениями конечных пользователей\n\t-\t⛓🕍[Cognito](https://aws.amazon.com/cognito/): Аутенфикация пользователей через Facebook, Twitter и т.д.\n\t-\t[Device Farm](https://aws.amazon.com/device-farm/): Тестирование облачных устройств \n\t-\t[Mobile Analytics](https://aws.amazon.com/mobileanalytics/): Решение для аналитики использования приложений\n\t-\t🕍[Mobile Hub](https://aws.amazon.com/mobile/): Комплексная управляемая среда для мобильной разработки\n-\t**Корпоративные сервисы:** Эти сервисы актуальны в случае, если у вас есть значительные потребности корпоративных облачных или гибридных сервисов. Многие небольшие компании и стартапы используют другие решения, такие как Google Apps или Box. Более крупные компании могут также использовать собственные не-AWS IT решения.\n\t-\t[AppStream](https://aws.amazon.com/appstream/): Приложения Windows в облаке, с доступом с множества различных устройств\n\t-\t[Workspaces](https://aws.amazon.com/workspaces/): Виртуальный рабочий стол Windows в облаке, с доступом с множества различных устройств\n\t-\t[WorkDocs](https://aws.amazon.com/workdocs/) (бывший Zocalo): Корпоративный документооборот\n\t-\t[WorkMail](https://aws.amazon.com/workmail/): Корпоративный почтовый сервис с функцией календаря\n\t-\t[Directory Service](https://aws.amazon.com/directoryservice/): Microsoft Active Directory в облаке\n\t-\t[Direct Connect](https://aws.amazon.com/directconnect/): Выделенное сетевое соединение между офисом или дата центром и AWS\n\t-\t[Storage Gateway](https://aws.amazon.com/storagegateway/): Соединение между локальным офисом и файловым хранилищем в AWS\n\t-\t[Service Catalog](https://aws.amazon.com/servicecatalog/): Управление каталогами IT сервисов и проверка соответствию требованиям\n-\t**Сервисы, которые вам, возможно, не нужно знать:** В конце скажем о том, что согласно нашему опросу, нижеприведенные сервисы не используются широко и часто по хорошим причинам:\n\t-\t[Snowball](https://aws.amazon.com/importexport/): Если вам необходимо переместить петабайты данных в/из Amazon используя физическое устройство, прочтите о нем.\n\t-\t[Snowmobile](https://aws.amazon.com/snowmobile/): Устройства это прекрасно, но если вам необходимо отправить в Amazon данные в масштабах экзабайт, ничто не сможет быть лучше чем трейлер набитый дисками. \n\t-\t[CodeCommit](https://aws.amazon.com/codecommit/): Git. Вы скорее всего уже используете GitHub или какое-то свое решение ([Stackshare](http://stackshare.io/stackups/github-vs-bitbucket-vs-aws-codecommit) предоставляет неофициальную статистику).\n\t-\t🕍[CodePipeline](https://aws.amazon.com/codepipeline/): Непрерывная интеграция. У вас наверняка уже есть другое решение.\n\t-\t🕍[CodeDeploy](https://aws.amazon.com/codedeploy/): Развертывание кода на серверах EC2. И снова, у вас наверняка есть другое решение.\n\t-\t🕍[OpsWorks](https://aws.amazon.com/opsworks/): Управление развертыванием используя Chef или (на ноябрь 2017) Puppet Enterprise.\n-\t[AWS in Plain English](https://www.expeditedssl.com/aws-in-plain-english) предлагает более дружественное объяснение, для чего нужны все остальные сервисы.\n\n### Инструменты и услуги, представленные на рынке\n\nСейчас на рынке столько облачных и ориентированных на “большие данные” корпоративных компаний, что редко кто может угнаться за этим. \n\nМы собрали инфографику из некоторых сервисов. Она далека от завершения, но пытается подчеркнуть сервисы, популярные среди практикующих работу с AWS - сервисы которые помогают работать конкретно с AWS или дополняют работу с ним, а также те инструменты, которые должен изучить каждый, работающий с AWS.\n\n![Популярные услуги и сервисы среди использующих AWS](../figures/aws-market-landscape.png)\n\n🚧 *Есть предложения по улучшению? Пожалуйста, [сообщите о проблеме](CONTRIBUTING.md).*\n\n\n### Общие понятия\n\n-\t📒 [**Общий справочник AWS**](https://docs.aws.amazon.com/general/latest/gr/Welcome.html) покрывает огромное количество общих понятий и концепций связанных с многими сервисами.\n-\tAWS позволяет производить развертывания в [**регионах(regions)**](https://docs.aws.amazon.com/general/latest/gr/rande.html), которые являются географически распределенными и изолированными месторасположениями, что позволяет снизить задержки и предлагает дополнительную отказоустойчивость. Регионы содержат зоны доступности (availability zones(AZs)), которые обычно является первым инструментом в выборе средств для обеспечения [высокой доступности](#высокая-доступность)). Зоны доступности [физически разделены друг от друга](https://www.youtube.com/watch?v=JIQETrFC_SQ&feature=youtu.be&t=1428) даже в одном и том же регионе, но [могут быть растянуты на несколько физических дата-центров](https://blog.rackspace.com/aws-101-regions-availability-zones). И хотя они связаны между собой каналами с низкой задержкой, стихийные бедствия, влияющие на одну из них, не должны затронуть другие.\n-\tУ каждого сервиса есть API **endpoints или точки приема запроса** для каждого региона. Точки приема запроса различаются от сервиса к сервису, кроме того, не все сервисы доступны в каждом регионе.Данные можно почерпнуть в [этих таблицах](https://docs.aws.amazon.com/general/latest/gr/rande.html).\n-\t[**Названия ресурсов Amazon(Amazon Resource Names (ARNs))**](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) это специальным образом отформатированные идентификаторы для идентификации ресурсов. Они начинаются с 'arn:' и используется во многих сервисах, в частности для политик в IAM.\n\n### Матрица сервисов\n\nМногие сервисы AWS как минимум могут быть сравнимы с предложениями Google Cloud иили внутренними сервисами Google. Также часто вы можете собрать подобный сервис используя программное обеспечение с открытым кодом. Эта таблица является попыткой перечислить эти грубые соответствия. (Помните, что эта таблица несовершенна, так как почти в каждом случае есть некоторые различия в функциях и особенностях!)\n\n| Сервис                       | AWS                                                                          | Google Cloud                 | Google Internal | Microsoft Azure                    | Другие провайдеры                   | “Построй сам” на открытом коде                               | Openstack     |\n|-------------------------------|------------------------------------------------------------------------------|------------------------------|-----------------|------------------------------------|-----------------------------------|------------------------------------------------------------|------------------------------------------------------------|\n| Virtual server                | EC2                                                                          | Compute Engine (GCE)         |                 | Virtual Machine                    | DigitalOcean                      | OpenStack                                                  | Nova |\n| PaaS                          | Elastic Beanstalk                                                            | App Engine                   | App Engine      | Web Apps                           | Heroku, AppFog, OpenShift | Meteor, AppScale, Cloud Foundry, Convox                    |\n| Serverless, microservices     | Lambda, API Gateway                                                          | Functions                    |                 | Function Apps                      | PubNub Blocks, Auth0 Webtask      | Kong, Tyk                                                  | Qinling |\n| Container, cluster manager    | ECS, EKS, Fargate                                                                 | Container Engine, Kubernetes | Borg or Omega   | Container Service                  |                                   | Kubernetes, Mesos, Aurora                                  |  Zun |\n| Object storage                  | S3                                                                           | Cloud Storage                | GFS             | Storage Account                    | DigitalOcean Spaces               | Swift, HDFS, Minio                                         | Swift |\n| Block storage                 | EBS                                                                          | Persistent Disk              |                 | Storage Account                    | DigitalOcean Volumes              | NFS                                                        | Cinder |\n| SQL datastore                 | RDS                                                                          | Cloud SQL                    |                 | SQL Database                       |                                   | MySQL, PostgreSQL                                          | Trove (stores NoSQL as well) |\n| Sharded RDBMS                 |                                                                              | Cloud Spanner                | F1, Spanner     | Azure Database for PostgreSQL - Hyperscale (Citus) |                                   | Crate.io, CockroachDB                                      |\n| Bigtable                      |                                                                              | Cloud Bigtable               | Bigtable        |                                    |                                   | HBase                                                      |\n| Key-value store, column store | DynamoDB                                                                     | Cloud Datastore              | Megastore       | Tables, DocumentDB                 |                                   | Cassandra, CouchDB, RethinkDB, Redis                       |\n| Memory cache                  | ElastiCache                                                                  | App Engine Memcache          |                 | Redis Cache                        |                                   | Memcached, Redis                                           |\n| Search                        | CloudSearch, Elasticsearch (managed)                                         |                              |                 | Search                             | Algolia, QBox, Elastic Cloud                     | Elasticsearch, Solr                                        |\n| Data warehouse                | Redshift                                                                     | BigQuery                     | Dremel          | SQL Data Warehouse                 | Oracle, IBM, SAP, HP, many others | Greenplum                                                  |\n| Business intelligence         | QuickSight                                                                   | Data Studio 360               |                 | Power BI                           | Tableau                           |                                                            |\n| Lock manager                  | [DynamoDB (weak)](https://gist.github.com/ryandotsmith/c95fd21fab91b0823328) |                              | Chubby          | Lease blobs in Storage Account     |                                   | ZooKeeper, Etcd, Consul                                    |\n| Message broker                | SQS, SNS, IoT                                                                | Pub/Sub                      | PubSub2         | Service Bus                        |                                   | RabbitMQ, Kafka, 0MQ                                       |\n| Streaming, distributed log    | Kinesis                                                                      | Dataflow                     | PubSub2         | Event Hubs                         |                                   | Kafka Streams, Apex, Flink, Spark Streaming, Storm         |\n| MapReduce                     | EMR                                                                          | Dataproc                     | MapReduce       | HDInsight, DataLake Analytics      | Qubole                            | Hadoop                                                     |\n| Monitoring                    | CloudWatch                                                                   | Stackdriver Monitoring       | Borgmon         | Monitor                            |                                   | Prometheus(?)                                              |\n| Tracing                       | X-Ray                                                                        | Stackdriver Trace            |                 | Monitor (Application Insights)     |  DataDog, New Relic, Epsagon      | Zipkin, Jaeger, Appdash\n| Metric management             |                                                                              |                              | Borgmon, TSDB   | Application Insights               |                                   | Graphite, InfluxDB, OpenTSDB, Grafana, Riemann, Prometheus |\n| CDN                           | CloudFront                                                                   | Cloud CDN                    |                 | CDN                                |  Akamai, Fastly, Cloudflare, Limelight Networks                                 | Apache Traffic Server                                      |\n| Load balancer                 | CLB/ALB                                                                      | Load Balancing               | GFE             | Load Balancer, Application Gateway |                                   | nginx, HAProxy, Apache Traffic Server                      |\n| DNS                           | Route53                                                                      | DNS                          |                 | DNS                                |                                   | bind                                                       |\n| Email                         | SES                                                                          |                              |                 |                                    | Sendgrid, Mandrill, Postmark      |                                                            |\n| Git hosting                   | CodeCommit                                                                   | Cloud Source Repositories    |                 | Visual Studio Team Services        | GitHub, BitBucket                 | GitLab                                                     |\n| User authentication           | Cognito                                                                      |    Firebase Authentication                          |                 | Azure Active Directory             |                                   | oauth.io                                                   |\n| Mobile app analytics          | Mobile Analytics                                                             | Firebase Analytics           |                 | HockeyApp                          | Mixpanel                          |                                                            |\n| Mobile app testing            | Device Farm                                                                  | Firebase Test Lab            |                 | Xamarin Test Cloud                 | BrowserStack, Sauce Labs, Testdroid                                                            |\n| Managing SSL/TLS certificates            | Certificate Manager                                                                  |                |                 |                 | Let's Encrypt, Comodo, Symantec, GlobalSign |\n| Automatic speech recognition and natural language understanding            | Transcribe (ASR), Lex (NLU)     | Cloud Speech API, Natural Language API             |                 | Cognitive services                | AYLIEN Text Analysis API, Ambiverse Natural Language Understanding API  |Stanford's Core NLP Suite, Apache OpenNLP, Apache UIMA, spaCy |\n| Text-to-speech engine in the cloud            | Polly                                                                  |                |                 |                 |Nuance, Vocalware, IBM | Mimic, eSpeak, MaryTTS |\n| Image recognition            | Rekognition                                                            |   Vision API              |                |Cognitive services                 | IBM Watson, Clarifai |TensorFlow, OpenCV |\n| OCR (Text recognition)       | Textract (documents), Rekognition (photographs)                               | Cloud Vision API             |                 | Computer Vision API                |                                   | Tesseract                                                  |\n| Language Translation          | Translate                                                                    | Translate                    |                 | Translator Text API                |                                   | Apertium                                                   |\n| File Share and Sync          | WorkDocs                                                                   |   Google Docs                 |                 |OneDrive                  |       Dropbox, Box, Citrix File Share                  |ownCloud |\n| Machine Learning          | SageMaker, DeepLens, ML                                                                   |   ML Engine, Auto ML                 |                 |ML Studio                  |       Watson ML                  |  |\n| Data Loss Prevention         | Macie                                                                         | Cloud Data Loss Prevention   |                | Azure Information Protection        |                                   |                                                            |\n\n🚧 [*Пожалуйста помогите заполнить таблицу*](CONTRIBUTING.md)\n\nВыбранные ресурсы более детализированно:\n\n-\tGoogle internal: [MapReduce](http://research.google.com/archive/mapreduce.html), [Bigtable](http://research.google.com/archive/bigtable.html), [Spanner](http://research.google.com/archive/spanner.html), [F1 vs Spanner](http://highscalability.com/blog/2013/10/8/f1-and-spanner-holistically-compared.html), [Bigtable vs Megastore](http://perspectives.mvdirona.com/2008/07/google-megastore/)\n\n### Зрелость продуктов AWS и выпуски\n\nВажно знать зрелость каждого продукта AWS. Это почти полный список дат первых выпусков, которые ссылаются на [примечания к выпуску](https://aws.amazon.com/releasenotes/). Наиболее молодые сервисы идут в списке первыми. Не все сервисы доступны во всех регионах; смотрите [эту таблицу](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/).\n\n| Сервис                                                                                                    | Первый выпуск | Доступность                                                                  | Поддержка CLI  | Соответствие HIPAA | Соответствие PCI-DSS  |\n|------------------------------------------------------------------------------------------------------------|------------------|-------------------------------------------------------------------------------|:-----------:|:---------------:|:-----------------:|\n| 🐥[X-Ray](https://aws.amazon.com/releasenotes/AWS-X-Ray?browse=1)\t\t\t\t\t\t\t\t\t\t  | 2016-12          | General\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  |✓            |✓                |✓                   |\n| 🐥[Lex](https://aws.amazon.com/releasenotes/Amazon-Lex?browse=1)                                           | 2016-11          | Preview                                                                       |             |                 |                   |\n| 🐥[Polly](https://aws.amazon.com/releasenotes/Amazon-Polly?browse=1)                                       | 2016-11          | General                                                                       |✓            |✓                |✓                   |\n| 🐥[Rekognition](https://aws.amazon.com/releasenotes/Amazon-Rekognition?browse=1) \t\t\t\t\t\t\t | 2016-11          | General                                                                       |✓            |✓\t\t\t\t |✓  \t\t\t\t|\n| 🐥[Athena](http://docs.aws.amazon.com/athena/latest/ug/what-is.html) \t\t\t\t\t\t\t\t\t\t | 2016-11          | General                                                                       |✓             |✓               |✓\t\t\t\t\t|\n| 🐥[Batch](http://docs.aws.amazon.com/batch/latest/userguide/what-is-batch.html) \t\t\t\t\t\t\t | 2016-11          | General                                                                       |✓             |✓\t\t\t|✓\t\t\t\t\t|\n| 🐥[Database Migration Service](https://aws.amazon.com/releasenotes/AWS-Database-Migration-Service?browse=1) | 2016-03          | General                                                                      |              | ✓         \t\t|\t✓    \t\t\t|\n| 🐥[Certificate Manager](https://aws.amazon.com/blogs/aws/new-aws-certificate-manager-deploy-ssltls-based-apps-on-aws/) | 2016-01          | General                                                            | ✓\t\t   |✓\t\t\t|✓\t\t\t\t\t|\n| 🐥[IoT](https://aws.amazon.com/blogs/aws/aws-iot-now-generally-available/)                                  | 2015-08          | General                                                                       | ✓           |✓\t\t\t|✓<sup>[13](#user-content-pci-iot)</sup>\t\t\t\t\t|\n| 🐥[WAF](https://aws.amazon.com/releasenotes/AWS-WAF?browse=1)                                               | 2015-10          | General                                                                       | ✓           | ✓         \t\t|\t✓    \t\t\t|\n| 🐥[Data Pipeline](https://aws.amazon.com/releasenotes/AWS-Data-Pipeline?browse=1)                           | 2015-10          | General                                                                       | ✓           |\t\t\t\t|\t\t\t\t\t|\n| 🐥[Elasticsearch](https://aws.amazon.com/releasenotes/Amazon-Elasticsearch-Service?browse=1)                | 2015-10          | General                                                                       | ✓           |✓\t\t\t|✓\t\t\t\t\t|\n| 🐥[Aurora](https://aws.amazon.com/releasenotes/2775579329314699)                                            | 2015-07          | General                                                                       | ✓           | ✓<sup>[3](#user-content-hipaa-aurora)</sup> |\t✓<sup>[3](#user-content-hipaa-aurora)</sup>\t\t\t|\n| 🐥[Service Catalog](https://aws.amazon.com/releasenotes/AWS-Service-Catalog?browse=1)                       | 2015-07          | General                                                                       | ✓           |✓\t\t\t|✓\t\t\t\t\t|\n| 🐥[Device Farm](https://aws.amazon.com/releasenotes/AWS-Device-Farm?browse=1)                         \t  | 2015-07          | General                                                                       | ✓           |\t\t\t\t|\t\t\t\t\t|\n| 🐥[CodePipeline](https://aws.amazon.com/releasenotes/AWS-CodePipeline?browse=1)                             | 2015-07          | General                                                                       | ✓           |✓\t\t\t|\t\t\t\t\t|\n| 🐥[CodeCommit](https://aws.amazon.com/releasenotes/AWS-CodeCommit?browse=1)                                 | 2015-07          | General                                                                       | ✓           |✓\t\t\t|✓\t\t\t\t\t|\n| 🐥[API Gateway](https://aws.amazon.com/releasenotes/Amazon-API-Gateway?browse=1)                            | 2015-07          | General                                                                       | ✓           | ✓<sup>[1](#user-content-hipaa-apigateway)</sup>  |\t ✓ \t\t\t|\n| 🐥[Config](https://aws.amazon.com/releasenotes/AWS-Config?browse=1)                                         | 2015-06          | General                                                                       | ✓           |✓                |  ✓              |\n| 🐥[EFS](https://aws.amazon.com/releasenotes/Amazon-EFS?browse=1)                                            | 2015-05          | General                                                                       | ✓           |✓                |✓                  |\n| 🐥[Machine Learning](https://aws.amazon.com/releasenotes/AmazonML?browse=1)                                 | 2015-04          | General                                                                       | ✓           |                 |                  |\n| [Lambda](https://aws.amazon.com/releasenotes/AWS-Lambda?browse=1)                                          | 2014-11          | General                                                                       | ✓           |✓                |   ✓             |\n| [ECS](https://aws.amazon.com/ecs/release-notes/)                                                           | 2014-11          | General                                                                       | ✓           | ✓         \t\t|\t✓   \t\t\t|\n| [EKS](https://docs.aws.amazon.com/eks/latest/userguide/platform-versions.html)                                                           | 2018-06          | General                                                                       | ✓<sup>[12](#user-content-eks-cli)</sup>           |✓         \t\t|✓\t  \t\t\t|\n| [KMS](https://aws.amazon.com/releasenotes/AWS-KMS?browse=1)                                                | 2014-11          | General                                                                       | ✓           |✓                |   ✓             |\n| [CodeDeploy](https://aws.amazon.com/releasenotes/AWS-CodeDeploy?browse=1)                                  | 2014-11          | General                                                                       | ✓           |✓                |                  |\n| [Kinesis](https://aws.amazon.com/releasenotes/Amazon-Kinesis?browse=1)                                     | 2013-12          | General                                                                       | ✓           |✓                |   ✓<sup>[11](#user-content-pci-kinesis)</sup>    |\n| [CloudTrail](https://aws.amazon.com/releasenotes/AWS-CloudTrail?browse=1)                                  | 2013-11          | General                                                                       | ✓           |✓                |   ✓             |\n| [AppStream](https://aws.amazon.com/releasenotes/Amazon-AppStream?browse=1)                                 | 2013-11          | Preview                                                                       |             |✓                |                  |\n| [CloudHSM](https://aws.amazon.com/releasenotes/AWS-CloudHSM?browse=1)                                      | 2013-03          | General                                                                       | ✓           |✓                |   ✓            |\n| [Silk](https://aws.amazon.com/releasenotes/Amazon-Silk?browse=1)                                           | 2013-03          | Obsolete?                                                                     |             |                 |                  |\n| [OpsWorks](https://aws.amazon.com/releasenotes/AWS-OpsWorks?browse=1)                                      | 2013-02          | General                                                                       | ✓           |✓                |   ✓             |\n| [Redshift](https://aws.amazon.com/releasenotes/Amazon-Redshift?browse=1)                                   | 2013-02          | General                                                                       | ✓           | ✓         \t\t|\t✓   \t\t\t|\n| [Elastic Transcoder](https://aws.amazon.com/releasenotes/Amazon-Elastic-Transcoder?browse=1)               | 2013-01          | General                                                                       | ✓           |                 |                  |\n| [Glacier](https://aws.amazon.com/releasenotes/Amazon-Glacier?browse=1)                                     | 2012-08          | General                                                                       | ✓           | ✓         \t\t|\t✓\t    \t\t|\n| [CloudSearch](https://aws.amazon.com/releasenotes/Amazon-CloudSearch?browse=1)                             | 2012-04          | General                                                                       | ✓           |                 |                  |\n| [SWF](https://aws.amazon.com/releasenotes/Amazon-SWF?browse=1)                                             | 2012-02          | General                                                                       | ✓           |✓                | ✓                |\n| [Storage Gateway](https://aws.amazon.com/releasenotes/AWS-Storage-Gateway?browse=1)                        | 2012-01          | General                                                                       | ✓           |✓                |✓                  |\n| [DynamoDB](https://aws.amazon.com/releasenotes/Amazon-DynamoDB?browse=1)                                   | 2012-01          | General                                                                       | ✓           | ✓         \t\t|\t  ✓  \t\t\t|\n| [DirectConnect](https://aws.amazon.com/releasenotes/AWS-Direct-Connect?browse=1)                           | 2011-08          | General                                                                       | ✓           | ✓         \t\t|\t✓   \t\t\t|\n| [ElastiCache](https://aws.amazon.com/releasenotes/Amazon-ElastiCache?browse=1)                             | 2011-08          | General                                                                       | ✓           |✓<sup>[14](#user-content-pci-elasticache)</sup> |✓<sup>[14](#user-content-pci-elasticache)</sup>                  |\n| [CloudFormation](https://aws.amazon.com/releasenotes/AWS-CloudFormation?browse=1)                          | 2011-04          | General                                                                       | ✓           |✓                |  ✓              |\n| [SES](https://aws.amazon.com/releasenotes/Amazon-SES?browse=1)                                             | 2011-01          | General                                                                       | ✓           |✓                |                  |\n| [Elastic Beanstalk](https://aws.amazon.com/releasenotes/AWS-Elastic-Beanstalk?browse=1)                    | 2010-12          | General                                                                       | ✓           |✓                |  ✓              |\n| [Route 53](https://aws.amazon.com/releasenotes/Amazon-Route-53?browse=1)                                   | 2010-10          | General                                                                       | ✓           |✓                | ✓               |\n| [IAM](https://aws.amazon.com/releasenotes/AWS-Identity-and-Access-Management?browse=1)                     | 2010-09          | General                                                                       | ✓           |                 |  ✓              |\n| [SNS](https://aws.amazon.com/releasenotes/Amazon-SNS?browse=1)                                             | 2010-04          | General                                                                       | ✓           | ✓         \t\t| ✓\t\t\t\t\t|\n| [EMR](https://aws.amazon.com/releasenotes/Elastic-MapReduce?browse=1)                                      | 2010-04          | General                                                                       | ✓           | ✓         \t\t|\t✓   \t\t\t|\n| [RDS](https://aws.amazon.com/releasenotes/Amazon-RDS?browse=1)                                             | 2009-12          | General                                                                       | ✓           |✓<sup>[2](#user-content-hipaa-rds)</sup>        |✓<sup>[9](#user-content-pci-rds)</sup>\t\t\t\t|\n| [VPC](https://aws.amazon.com/releasenotes/Amazon-VPC?browse=1)                                             | 2009-08          | General                                                                       | ✓           | ✓         \t\t|\t✓   \t\t\t|\n| [Snowball](https://aws.amazon.com/releasenotes/AWS-ImportExport?browse=1)                                  | 2015-10          | General                                                                       | ✓           | ✓         \t\t|✓<sup>[15](#user-content-pci-snowball)</sup>\t\t\t\t\t|\n| [Snowmobile](https://aws.amazon.com/snowmobile/)                                                           | 2016-11          | General                                                                       |            |✓                |✓                  |\n| [CloudWatch](https://aws.amazon.com/releasenotes/CloudWatch?browse=1)                                      | 2009-05          | General                                                                       | ✓           |✓                |  ✓               |\n| [CloudFront](https://aws.amazon.com/releasenotes/CloudFront?browse=1)                                      | 2008-11          | General                                                                       | ✓           | ✓<sup>[4](#user-content-hipaa-cloudfront)</sup>        |  ✓\t\t\t\t|\n| [Fulfillment Web Service](https://aws.amazon.com/releasenotes/Amazon-FWS?browse=1)                         | 2008-03          | Obsolete?                                                                     |             |                 |                  |\n| [SimpleDB](https://aws.amazon.com/releasenotes/Amazon-SimpleDB?browse=1)                                   | 2007-12          | ❗[Nearly obsolete](https://forums.aws.amazon.com/thread.jspa?threadID=121711) | ✓           |                 |  ✓              |\n| [DevPay](https://aws.amazon.com/releasenotes/DevPay?browse=1)                                              | 2007-12          | General                                                                       |             |                 |                  |\n| [Flexible Payments Service](https://aws.amazon.com/releasenotes/Amazon-FPS?browse=1)                       | 2007-08          | Retired                                                                       |             |                 |                  |\n| [EC2](https://aws.amazon.com/releasenotes/Amazon-EC2?browse=1)                                             | 2006-08          | General                                                                       | ✓           | ✓<sup>[5](#user-content-hipaa-ec2sysmgr),[6](#user-content-hipaa-ec2ebs),[7](#user-content-hipaa-ec2elb)</sup>          |\t✓<sup>[6](#user-content-hipaa-ec2ebs),[7](#user-content-hipaa-ec2elb),[10](#user-content-pci-asg)</sup>\t\t\t|\n| [SQS](https://aws.amazon.com/releasenotes/Amazon-SQS?browse=1)                                             | 2006-07          | General                                                                       | ✓           | ✓         \t\t| ✓               |\n| [S3](https://aws.amazon.com/releasenotes/Amazon-S3?browse=1)                                               | 2006-03          | General                                                                       | ✓           | ✓<sup>[8](#user-content-hipaa-s3)</sup>   |\t✓   \t\t\t|\n| [Alexa Top Sites](https://aws.amazon.com/alexa-top-sites/)                                                 | 2006-01          | General ❗HTTP-only                                                            |             |                 |                  |\n| [Alexa Web Information Service](https://aws.amazon.com/awis/)                                              | 2005-10          | General ❗HTTP-only                                                            |             |                 |                  |\n\n##### Примечания\n<a name=\"user-content-hipaa-apigateway\">**1**</a>: Исключая Amazon API Gateway caching<br />\n<a name=\"user-content-hipaa-rds\">**2**</a>: Только для RDS MySQL, Oracle, и PostgreSQL<br />\n<a name=\"user-content-hipaa-aurora\">**3**</a>: Только для MySQL-совместимой Aurora<br />\n<a name=\"user-content-hipaa-cloudfront\">**4**</a>: Исключая Lambda@Edge<br />\n<a name=\"user-content-hipaa-ec2sysmgr\">**5**</a>: Включает в себя EC2 Systems Manager<br />\n<a name=\"user-content-hipaa-ec2ebs\">**6**</a>: Включая Elastic Block Storage (EBS)<br />\n<a name=\"user-content-hipaa-ec2elb\">**7**</a>: Включая Elastic Load Balancing<br />\n<a name=\"user-content-hipaa-s3\">**8**</a>: Включая S3 Transfer Acceleration<br />\n<a name=\"user-content-pci-rds\">**9**</a>: Включая RDS MySQL, Oracle, PostgreSQL, SQL Server и MariaDB</br>\n<a name=\"user-content-pci-asg\">**10**</a>: Включая Автоматическое масштабирование(Auto-Scaling)</br>\n<a name=\"user-content-pci-kinesis\">**11**</a>: Data Analytics, Streams, Video Streams и Firehose</br>\n<a name=\"user-content-eks-cli\">**12**</a>: Kubernetes использует свой CLI для управления подами и службами, называемый kubectl. AWS CLI необходима только для работы с Kubernetes Master</br>\n<a name=\"user-content-pci-iot\">**13**</a>: IoT Core (включая управление устройствами) и Greengrass</br>\n<a name=\"user-content-pci-elasticache\">**14**</a>: Только ElastiCache с Redis</br>\n<a name=\"user-content-pci-snowball\">**15**</a>: Snowball и Snowball Edge</br>\n\n\n### Соответствие стандартам и регулирующим документам\n\n-\tМногие приложения имеют строгие требования относительно надежности, безопасности и приватности данных. Страница [AWS Compliance](https://aws.amazon.com/compliance/) содержит все детали о сертификациях AWS в области соответствия, включая **PCI DSS Level 1**, **SOC 1,2, and 3**, **HIPAA**, и **ISO 9001**.\n-\tБезопасность в облаке - сложная тема, основывающаяся на [модели распределенной ответственности(shared responsibility model)](https://aws.amazon.com/compliance/shared-responsibility-model/), где некоторые элементы соответствия достигаются за счет усилий AWS, а некоторые за счет ваших усилий и вашей компании.\n-\tНекотороые сторонние поставщики предлагаю помощь в обеспечении соответствия, безопасности и проведения аудита на AWS. Если у вас есть существенная потребность, то помощь - это хорошая идея.\n-\tС континентального **Китая**, сервисы AWS расположеннные вне Китая [в большинстве своем доступны](https://en.greatfire.org/aws.amazon.com), за исключением отдельных временных разрывов доступа. Также имеются сервисы AWS расположенные [в Китае](https://www.amazonaws.cn/en/).\n\n### Получение помощи и поддержки\n\n-\t**Форумы:** Для решения многих проблем, возможно стоит сначала поискать решение в интернете или попросить помощи на [дискуссионных форумах](https://forums.aws.amazon.com/index.jspa), так как скорее всего - это уже известная проблема.\n-\t**Премиум поддержка:** AWS предлагает несколько уровней [премиум поддержки](https://aws.amazon.com/premiumsupport/).\n\t-\tПервый уровень, называемый \"Поддержка разработчиков\" позволяет вам открывать тикеты в службе поддержки с временем обработки от 12 до 24 часов, расценки на данный уровень начинаются с $29 в месяц, но как только ваши месячные расходы превышают $1000, оплата за данный уровень поддержки составит 3% от ваших общих расходов.\n\t-\tБолее высокие уровни поддержки довольно таки дороги и могут увеличить сумму в счете на 10%. Многие крупные и эффективные компании никогда не платят за такие уровни поддержки. Они больше полезны для средних и крупных компаний, которым необходимо крайне быстрое решение сложных и глубоких проблем. \n\t-\tИмейте в виду, что гибкая архитектура может снизить потребность в поддержке. Вы не должны полагаться на то, чтобы AWS часто решало ваши проблемы. Например, если вы с легкостью можете переразвернуть новый сервер, возможно не так уж и срочно стоит решать редкую или даже уникальную проблему на уровне ядра, которая затрагивает только один инстанс EC2. Если у вас есть недавние снапшоты томов EBS, возможно восстановить том будет быстрее, нежели поддержка устранит проблему со старым томом. Если у вас есть какая-либо проблема в одной зоне доступности, в таком случае вы можете положиться на отказоустойчивую стенд-бай зону или смигировать сервисы в другую зону доступности. \n\t-\tКрупные клиенты также получают доступ к корпоративной поддержке AWS, со специально выделенным техническим менеджером по работе с клиентами(TAM - Technical account manager) и SLA с более коротким временем реакции.\n\t-\tОпределенно есть некоторые контраргументы относительно полезности платной поддержки. Сотрудники службы поддержки не всегда обладают достаточной информацией и полномочиями для решения определенного рода проблем, которые могут у вас возникать. Часто скорость и возможность решения проблем зависит от взаимоотношений с вашим аккаунт менеджером.\n-\t**Аккаунт менеджер:** Если вы тратите значительные средства ( тысячи долларов в месяц), вам может быть назначен ( или вы можете запросить самостоятельно) выделенный аккаунт менеджер. \n\t-\tЭто действительно великолепный ресурс, даже если вы не платите за премиум поддержку. Выстройте с ними хорошие отношения и используйте их для решения вопросов, проблем и получения рекомендаций.\n\t-\tНазначьте ответственного за контакты с AWS со стороны своей компании, для избежания путаницы и двойной работы.\n-\t**Контакты:** Основная точка контакта с AWS [тут](https://aws.amazon.com/contact-us/). Многие технические вопросы могут быть решены посредством этих каналов связи.\n-\t**Консультанты и компании предоставляющие управляющие услуги:** Для получения дополнительной помощи на местах, AWS установила отношения со многими [партнерами-консалтерами](https://aws.amazon.com/partners/consulting/) и [партнерами по управлению услугами(ИТ управляющие компании)](https://aws.amazon.com/partners/msp/). Крупные консалтеры недешевы, однако, в зависимости от ваших потребностей, могут снизить ваши затраты в долгосрочном периоде путем более эффективного проектирования вашей архитектуры или предложения конкретный опыт, например безопасность. Поставщики управляемых услуг предоставляют долгосрочное полное управление облачными ресурсами. \n-\t**AWS Professional Services:** AWS предоставляет [консультационные услуги](https://aws.amazon.com/professional-services/) самостоятельно или совместно с партнерами.\n\n### Ограничения и другие заметки\n\n-\t🔸Многие ресурсы в Amazon имеют [**определенные ограничения**](http://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html) при использовании. В действительности это полезно, таким образом вы не понесете больших расходов случайно. Чтобы запросить увеличение квот, необходимо оставить заявку в службе поддержки. Некоторые ограничения легко увеличить, некоторые нет.  (Некоторые из них отмечены в разделах ниже.) В дополнение, не все ограничения опубликованы.\n\t- **Получение информации о текущих ограничениях и их использовании:** Информация об ограничении для сервиса может быть доступна с API сервиса, Trusted Advisor, из них обоих или ни из одного из них (в это случае вам необходимо связаться с поддержкой). [Эта страница](http://awslimitchecker.readthedocs.io/en/latest/limits.html) из документации инструмента awslimitchecker предоставляет хороший обзор возможных средств для получения информации для каждого ограничения. [Этот инструмент](https://github.com/jantman/awslimitchecker) также является очень полезным для автоматизации проверок ограничений. \n-\t🔸[**Условия обслуживания AWS**](https://aws.amazon.com/service-terms/) обширны. Большая часть - шаблонна, однако имеются довольно таки важные заметки и ограничения по каждому сервису. В частности, есть ограничение на использование многих сервисов AWS в  **жизненно важных системах**. (Те, кто ценит юридический юмор, могут рассмотреть [пункт 42.10.](https://www.theguardian.com/technology/2016/feb/11/amazon-terms-of-service-zombie-apocalypse)) \n\n### Сопутствующие темы\n\n-\t[OpenStack](https://www.openstack.org/) это альтернативное AWS частное облако используемое крупными компаниями, которые хотят избежать использования предлагаемых публичных облачных решений.\n\nОбучение и карьерное развитие\n-------------------------------\n\n### Сертификации\n\n-\t**Сертификации:** AWS предлагают [**сертификации**](https://aws.amazon.com/certification/) для профессионалов в IT, которые хотят продемонстрировать свои знания.\n  -\t[Certified Cloud Practitioner](https://aws.amazon.com/certification/certified-cloud-practitioner/)\n  -\t[Certified Solutions Architect Associate](https://aws.amazon.com/certification/certified-solutions-architect-associate/)\n  -\t[Certified Developer Associate](https://aws.amazon.com/certification/certified-developer-associate/)\n  -\t[Certified SysOps Administrator Associate](https://aws.amazon.com/certification/certified-sysops-admin-associate/)\n  -\t[Certified Solutions Architect Professional](https://aws.amazon.com/certification/certified-solutions-architect-professional/)\n  -\t[Certified DevOps Engineer Professional](https://aws.amazon.com/certification/certified-devops-engineer-professional/)\n  - [Certified Security – Specialty](https://aws.amazon.com/certification/certified-security-specialty/)\n  - [Certified Big Data – Specialty](https://aws.amazon.com/certification/certified-big-data-specialty/)\n  - [Certified Advanced Networking – Specialty](https://aws.amazon.com/certification/certified-advanced-networking-specialty/)\n  - [Certified Machine Learning – Specialty](https://aws.amazon.com/certification/certified-machine-learning-specialty/)\n  - [Certified Alexa Skill Builder – Specialty](https://aws.amazon.com/certification/certified-alexa-skill-builder-specialty/)\n  - [Certified Data Analytics – Specialty](https://aws.amazon.com/certification/certified-data-analytics-specialty/)\n  - [Certified Database – Specialty](https://aws.amazon.com/certification/certified-database-specialty/)\n  \n\nСертификации младшего звена(Associate) ранее были обязательным требования для сдачи экзаменов профессионального уровня, сейчас это не так.\n\n-\t**Получение сертификата и статуса:** Если вы заинтересованы в обучении и прохождении сертификационных экзаменов с получением статуса сертифицированного специалиста, [этот практический обзор](https://gist.github.com/leonardofed/bbf6459ad154ad5215d354f3825435dc) расскажет вам многое из того, что вам необходимо знать. Официальная страница обучения и сертификации AWS [тут](https://aws.amazon.com/training/), также есть страница с ответами на ЧАсто задаваемые ВОпросы [ЧАВО](https://aws.amazon.com/certification/faqs/).\n-\t**Тренинги для сертификации:** AWS предлагает собственные тренинги (в основном проводящиеся инструктором на базе предприятия заказчика), кроме того, множество сторонних компаний предлагают свои коммерческие тренинги (обычно в виде видео-курсов), к примеру [A Cloud Guru](https://acloud.guru/aws-cloud-training), [CloudAcademy](https://cloudacademy.com/library/amazon-web-services/) and [Linux Academy](https://linuxacademy.com/library/topics/AWS/type/Course/).\n-\t**Необходима ли вам сертификация?** Если вы работаете на ключевых технических ролях в не-технологических компаниях, или, и даже в особенности, если вы работаете в консалтерских компаниях - сертификат является важным документом, подтверждающим вашу экспертизу. С другой стороны, во многих технологических компаниях и стартапах, сертификаты не обязательны. (На деле, справедливо это или нет, некоторые HR-менеджера и нанимающие специалисты из Силиконовой Долины считают сертификаты “плохим” фактором в резюме.)\n\nСертификаты необходимы для доступа в ложи сертифицированных специалистов на официальных мероприятиях AWS, таких как [Summits](https://aws.amazon.com/events/summits/) и [re:Invent](https://reinvent.awsevents.com). В ложах обычно предоставляются розетки электропитания, кресла, ну и к слову, кофе у них гораздо лучше.\n\nУправление AWS\n------------\n\n### Управление состоянием инфраструктуры и изменениями\n\nСерьезной проблемой в использовании AWS при построении сложных систем (и с DevOps в целом) является эффективное управление состоянием инфраструктуры на протяжении всего времени использования. В целом это сводится к трем основным целям состояния инфраструктуры:\n\n-\t**Видимость**: Знаете ли вы состояние вашей инфраструктуры (какие сервисы вы используете и как именно)? Знаете ли вы также, когда вы или кто-либо из вашей команды вносит изменения? Можете ли вы определить проблемы, неправильные настройки и инциденты связанные с вашими сервисами?\n-\t**Автоматизация**: Можете ли вы перенастроить вашу инфраструктуру, чтобы повторить прошлые конфигурации или масштабировать текущую без большого количества ручной работы или знаний, которые есть только у кого-то в голове? Можете ли вы реагировать на инциденты быстро и легко или вообще автоматически?\n-\t**Гибкость**: Можете ли вы улучшить свою конфигурацию или масштабировать ее новыми способами без значительных усилий? Можете ли вы добавить сложности используя те же самые инструменты? Делитесь ли вы знаниям о конфигурации, пересматриваете и улучшаете ее со своей командой?\n\nМного из того, о чем пойдет речь ниже о том, как лучшим образом ответить на все эти вопросы.\n\nЕсть несколько подходов по развертыванию инфраструктуры в AWS, начиная с консоли до сложных инструментов автоматизации, сторонних служб, цель которых помочь достичь видимости, автоматизации и гибкости. \n\n### Управление конфигурацией AWS\n\nПоначалу большинство людей экспериментируют с AWS через веб-интерфейс, AWS Console. Но использование консоли(AWS Console) - в основном ручной процесс, что часто работает против автоматизации и гибкости.\n\nТак что, если вы не собираетесь управлять AWS вручную, что же вам делать? К сожалению, тут нет простого, универсального ответа - каждый подход имеет свои плюсы и минусы, и подходы разных компаний различаются очень широко и включают в себя прямое использование API (и построение своих инструментов поверх самостоятельно), использование утилит в командной строке, а также сторонних решений и сервисов.\n\n### AWS Console\n\n-\t[AWS Console](https://aws.amazon.com/console/) позволяет вам контролировать большинство (но не весь) функционала AWS через веб-интерфейс.\n-\tВ идеале консоль AWS стоит использовать только в некоторых конкретных случаях:\n\t-\tОна отлично подходит для использования в режиме только для чтения. Если вы пытаетесь понять состояние вашей системы, вход в консоль и ее просмотр будет очень полезен. \n\t-\tЭто также разумно для очень маленьких систем и команд (для примера, один инженер устанавливает один сервер, который не часто меняется и перенастраивается).\n\t-\tЭто также может быть полезно для действий, которые вы делаете крайне редко, например реже раза в месяц (как пример, одноразовая настройка VPC, вы возможно не вернетесь к ней в течении года). В таком случае использование консоли будет простейшим подходом. \n-\t❗**Подумайте прежде чем использовать консоль:** AWS консоль удобна, но является врагом автоматизации, The AWS Console is convenient, but also the enemy of automation, воспроизводимости и командных коммуникаций. Если вы, скорее всего, будете делать одну и ту же вещь множество раз, избегайте консоли. Проявите интерес к какой нибудь автоматизации или хотя бы наметьте путь к автоматизации, о которой речь пойдет ниже. Использование консоли не только исключает автоматизацию, что в свою очередь ведет к пустым потерям времени в дальнейшем, но также ведет к предотвращению нормального документирования, ясности и стандартизации процессов для вас и вашей команды. \n\n### Инструменты командной строки\n\n-\t[**Интерфейс командной строки AWS**](https://aws.amazon.com/cli/) (AWS CLI), используемые через комманду **aws**, это самый простой способ автоматизировать управление AWS.\n-\tНе стоит недооценивать его мощь. Его преимущество заключается в том, что он постоянно поддерживается в хорошем состоянии - он покрывает большую часть всех сервисов AWS и регулярно обновляется. \n-\tВ общем, выбирайте командную строку, вместо консоли во всех случаях, когда это возможно. \n-\t🔹Даже в случае отсутствия более изящных инструментов, вы можете **написать простые скрипты на Bash** которые вызывают *aws* с конкретными аргументами, а потом сохранить их в Git. Это простейший, но очень эффективный способ документировать выполненные операции. Это повышает автоматизацию, позволяет проводить код-ревью и делиться с командой, что дает остальным хороший старт для будущей работы.\n-\t🔹Если вы хотите работать интерактивно (а не через скрипты), попробуйте использовать инструмент [**aws-shell**](https://github.com/awslabs/aws-shell) от AWS. Он прост в использовании, с автозавершением команд и цветным интерфейсом, но также работает в командной строке. Если вы используете [SAWS](https://github.com/donnemartin/saws), предыдущую версию данной программы, [вам стоит перейти на aws-shell](https://github.com/donnemartin/saws/issues/68#issuecomment-240067034).\n\n### API-интерфейсы и наборы средств разработки(SDK)\n\n-\t**Наборы средств разработки(SDK)** для использования API-интерфейсов в AWS APIs доступны в большинстве основных языков, причем [Go](https://github.com/aws/aws-sdk-go), [iOS](https://github.com/aws/aws-sdk-ios), [Java](https://github.com/aws/aws-sdk-java), [JavaScript](https://github.com/aws/aws-sdk-js), [Python](https://github.com/boto/boto3), [Ruby](https://github.com/aws/aws-sdk-ruby) и [PHP](https://github.com/aws/aws-sdk-php) наиболее широко используются. AWS поддерживает свой [шорт-лист](https://aws.amazon.com/tools/#sdk), однако [список awesome-aws](https://github.com/donnemartin/awesome-aws#sdks-and-samples) наиболее полный и актуальный. К сведению,  [поддержка C++](https://github.com/donnemartin/awesome-aws#c-sdk) является [относительно новой](https://aws.amazon.com/blogs/aws/introducing-the-aws-sdk-for-c/).\n-\t**Логика повторов:** Важным аспектом при использовании SDK, котороый необходимо учитывать, являяется обработка ошибок;  при интенсивном использовании, может произойти множество отказов и ошибок, начиная с ошибок программирования и троттлинга(пропуска запросов), до связанных с AWS отказов сервисов. SDK обычно реализуют [**экспоненциальный откат(плавное и мультипликативное снижение частоты запросов для нахождения не затрагивающей работоспособность системы частоты запросов)**](https://docs.aws.amazon.com/general/latest/gr/api-retries.html) для решения этой проблемы, однако это требует понимания и настройки время от времени для некоторых приложений. Например, часто является полезным оповещение об одних типах ошибок и отсутствие оповещения о других.\n-\t❗Не используйте API напрямую. Несмотря на то, что документация AWS содержит в себе множество инфорамции о API, все равно лучше использовать SDK на вашем предпочитаемом языке программирования для доступа к API-интерфейсам. SDK более зрелые, надежные и более хорошо поддерживаются, нежели то, что вы напишете сами.\n\n### Boto\n\n-\tХорошим способом автоматизировать операции в AWS пользователем - является использование [**Boto3**](https://github.com/boto/boto3), также известного, как [Amazon SDK for Python](http://aws.amazon.com/sdk-for-python/). [**Boto2**](https://github.com/boto/boto) - прошлая версия этой библиотеки широко использовалась в течении многих лет, но сейчас есть более новая версия с официальной поддержкой от Amazon, так что есть смысл предпочесть Boto3 для новых проектов.\n-\tBoto3 содержит множество API, которые работают либо на высоком, либо на низком уровне, ниже пояснения об обоих уровнях:\n\t-\tНизкоуровневые API (Клиентские API) сопоставляются с API-интерфейсами облачных сервисов AWS , и все сервисные операции поддерживаются клиентами. Клиенты генерируются из файлов описания сервисов в формате JSON.\n\t-\tВысокоуровневая опция - Ресурсные API, позволяет вам избежать вызова сети на низком уровне, а вместо этого предоставляет объектно-ориентированный способ взаимодействия с облачными сервисами AWS.\n-\tУ Boto3 есть множество полезных [**функций**](https://boto3.readthedocs.io/en/latest/guide/index.html#general-feature-guides), например  *ожидания(waiters)*, которая предоставляет такую структуру, которая позволяет коду ожидать изменений в облаке прежде, чем продолжать выполнение, например, когда вы создаете EC2 инстанс и хотите дождаться пока инстанс запустится, чтобы запустить следующую задачу.\n-\tЕсли вы пишете Bash скрипт с одной или более CLI команд, возможно вы делаете это неправильно. Остановитесь и подумайте о написании Boto скрипта вместо этого. Тут имеются следующие преимущества:\n\t-\tЛегкая проверка кодов ответа, таким образом успех каждого шага зависит от успеха предыдущих.\n\t-\tПолучайте интересующие вас фрагменты данных из ответов, такие как идентификатор инстанса или DNS имя.\n\t-\tДобавьте полезную информацию об окружении (например, пометьте(тэгируйте) свои инстансы с помощью git-ревизий или вставьте последний идентификатор сборки в ваш скрипт инициализации).\n\n### Общая видимость\n\n-\t🔹[**Пометка ресурсов(тегирование)**](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) - это весьма важная практика, особенно при росте организации, для лучшего понимания использования ресурсов. Например, посредством автоматизации и соглашения об именовании, вы можете добавлять пометки(тэги): \n\t-\tДля организации или разработчиков, которые “владеют” этим ресурсом\n\t-\tДля продукта, который расположен на данном ресурсе\n\t-\tДля маркировки жизненного цикла ресурса, к примеру временных ресурсов или тех, которые должны быть отключены и удалены в будущем \n\t-\tДля того, чтобы различать критично важную для производства инфраструктуру(например, обслуживающие системы или бэкенд)\n\t-\tДля того, чтобы различать системы со специальными требованиями по безопасности или требованиям соотвествиям стандартам и политикам\n\t-\tДля того, чтобы (после включения) [распределить стоимость в счетах](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html). Имейте ввиду, что использование меток(тэгов) для распределения стоимости работает только на перспективной основе; вы не можете задним числом применить их к ресурсам, счета на которые уже выставлены.\n\t-\tВ течении многих лет существовал пресловутый лимит на 10 меток(тэгов) на ресурс, который нельзя было увеличить, что причиняло серьезные страдания многим компаниям. По состоянию на 2016 год, лимит [был увеличен](https://aws.amazon.com/blogs/security/now-organize-your-aws-resources-by-using-up-to-50-tags-per-resource/) до 50 меток(тэгов) на ресурс.\n\t-\t🔹В 2017 AWS представило возможность [форсированного применения меток(тэгирования)](https://aws.amazon.com/blogs/aws/new-tag-ec2-instances-ebs-volumes-on-creation/) при создании инстансов и томов, что сделало бесполезными некоторые сторонние инструменты, такие как [Cloud Custodian](https://github.com/capitalone/cloud-custodian).\n\t-\t🔸 Метки(тэги) чувствительны к регистру; 'environment' и 'Environment' - это две разных метки(тэга). Автоматизация при установке меток(тэгов) скорее всего единственный разумный вариант в значительных масштабах. \n\t-\t🔸 В консоли ASG есть баг, пробелы после имени метки(тэга) сохраняются. Таким образом если вы введете \"Name \" с пробелом на конце, вы не получите ожидаемого результата. Также существует возможность, что баг существует в других местах и SDK. Удостоверьтесь, что вы не добавляете пробелы в конце имени метки, кроме случаев, когда вам это действительно необходимо. (По состоянию на июль 2018 года)\n\nУправление серверами и приложениями\n---------------------------------\n\n### AWS и конфигурация серверов\n\nЭто руководство посвящено AWS, а не DevOps или управлению конфигурацией серверов в общем. Но прежде чем углубляться в AWS, стоит отметить, что в дополнение к управлению конфигурацией ваших ресурсов AWS существует давняя проблема управления конфигурацией для самих серверов.\n\n### Философия\n\n-\tВ принципах [**Двеннадцати-факторного приложения**](http://12factor.net/) от Heroku перечислены некоторые общепринятые рекомендации по развертыванию приложений.\n-\t**Домашние любимцы и скот:** Относитесь к серверам [как к скоту, а не как к домашнему любимцу](https://www.engineyard.com/blog/pets-vs-cattle). Таким образом, проектируйте систему так, как будто инфраструктура одноразовая. Таким образом неожиданная потеря сервера не должна вызывать серьезного беспокойства.\n-\tКонцепция [**неизменной инфраструктуры**](http://radar.oreilly.com/2015/06/an-introduction-to-immutable-infrastructure.html) является продолжением этой идеи.\n-\tМинимизируйте размещение приложений на EC2 инстансах. В целом, инстансы могут умереть или быть выключены, или удалены с минимальным влиянием на приложения. Данные вашего приложение должны быть перемещены в RDS, S3, DynamoDB, EFS, или любое другое хранилище данных, не зависящее от инстанса. EBS также является вариантом, хотя это не должен быть загрузочный том, а также EBS потребует ручного или автоматического переподключения.\n\n### Управление конфигурацией серверов\n\n-\tСуществует [большой набор](https://en.wikipedia.org/wiki/Comparison_of_open-source_configuration_management_software) инструментов с открытым кодом, для управления конфигурацией серверных инстансов. \n-\tОни, как правило, не зависят от конкретной облачной инфраструктуры и работают с множеством различных вариаций Linux дистрибутивов (или, во многих случаях, с множеством операционных систем).\n-\tЛидирующими инструментами управления конфигурациями являются [Puppet](https://github.com/puppetlabs/puppet), [Chef](https://github.com/chef/chef), [Ansible](https://github.com/ansible/ansible), и [Saltstack](https://github.com/saltstack/salt). Они не являются предметом данного руководства, но мы можем упомянуть их, поскольку они относятся к AWS.\n\n### Контейнера и AWS\n\n-\t[Docker](http://blog.scottlowe.org/2014/03/11/a-quick-introduction-to-docker/) aи тенденция контейнеризации меняет способ развертывания многих серверов и служб в целом.\n-\tКонтейнеры предназначены для того, чтобы известным способом упаковать ваши приложения и все их зависимости. Когда вы создаете контейнер, вы включаете каждую библиотеку или двоичный файл, которые нужны вашему приложению, помимо ядра. Большим преимуществом этого подхода является легкость тестирования и проверки контейнера локально, не беспокоясь о разнице конфигурации между вашим локальным компьютером и серверами, на которых вы развертываете приложение.\n-\tСледствием этого подхода является то, что вам требуется меньшее количество образов виртуальных машин AWS(AMI) и загрузочных скриптов; для большинства развертываний единственным загрузочным скриптом, который вам понадобится, является шаблон который подтягивает экспортированный образ Docker-контейнера и запускает его.\n-\tКомпании, использующие [микросервисные инфраструктуры](http://martinfowler.com/articles/microservices.html) часто выбирают контейнерное развертывание.\n-\tAWS запустил [ECS](https://aws.amazon.com/ecs/) - сервис управляющий кластерами Docker в конце 2014 года, хотя многие люди до сих пор используют Docker непосредственно напрямую. Подробности смотрите в [разделе ECS](#ecs).\n-\tAWS запустил [EKS](https://aws.amazon.com/eks/) сервис управляющий кластерами Kubernetes в середине 2018 года, хотя многие люди до сих пор разворачивают кластера используя ECS или самостоятельно используют непосредственно Docker. Подробности смотрите в [разделе EKS ](#eks).\n\n### Видимость\n\n-\tХраните и отслеживайте метаданнные инстанса (такие как идентификатор инстанса, зона доступности, и т.д.) и информацию о развертывании (идентификатор сборки приложения, ревизия Git, и т.д.) в ваших лог-файлах и отчетах. [**Сервис метаданных инстансов(instance metadata service)**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) может помочь собрать часть необходимых данных о ресурсах AWS.\n-\t**Используйте сервисы управления лог-файлами:** Обязательно настройте способ просмотра и управления логами вне серверов.\n\t-\tОблачные сервисы, такие как [Sumo Logic](https://www.sumologic.com/), [Splunk Cloud](http://www.splunk.com/en_us/cloud.html), [Scalyr](https://www.scalyr.com/), [LogDNA](https://www.logdna.com/), и [Loggly](https://www.loggly.com/) самые простые в настройке и использовании (а также самые дорогие, что может быть факторов против их использования, в зависимости от количества логов, которые необходимо хранить).\n\t-\tОсновные альтернативы с открытым исходным кодом включают [Elasticsearch](https://github.com/elastic/elasticsearch), [Logstash](https://github.com/elastic/logstash), и [Kibana](https://github.com/elastic/kibana) (так называемый “[Elastic Stack](https://www.elastic.co/webinars/introduction-elk-stack)”) и [Graylog](https://www.graylog.org/).\n\t-\tЕсли вы можете себе это позволить (например, у вас мало данных или много денег) и у вас нет особых потребностей, имеет смысл использовать хостинговые сервисы, когда это возможно, поскольку установка ваших собственных масштабируемых систем обработки логов занимает много времени.\n-\t**Отслеживание и визуализация метрик:** AWS Консоль может показать вам простые графики из CloudWatch, вы также можете пожелать отслеживать и визуализировать многие виды метрик, как из CloudWatch, так и из вашего приложения. Собирайте и экспортируйте полезные метрики везде, где можете (и если объем логов достаточно управляем, вы можете себе это позволить).\n\t-\tСервисы вроде [Librato](https://www.librato.com/), [KeenIO](https://keen.io/), и [Datadog](https://www.datadoghq.com/) имеют более интересные функции и более удобные пользовательские интерфейсы, что может сохранить много времени. (Более детальное сравнение [тут](http://blog.takipi.com/production-tools-guide/visualization-and-metrics/).)\n\t-\tИспользуйте [Prometheus](https://prometheus.io) или [Graphite](https://github.com/graphite-project/graphite-web) как базы данных временных рядов для ваших метрик (оба варианта с открытым исходным кодом).\n\t-\t[Grafana](https://github.com/grafana/grafana) может визуализировать с помощью инструментальных панелей(дашбордов) сохраненные метрики из обеих баз данных временных рядов (также с открытым исходным кодом).\n\n### Советы по управлению серверами\n\n-\t❗**Настройки часового пояса на серверах**: Кроме случаев *абсолютной необходимости*, всегда **устанавливайте часовой пояс на серверах в [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time)** (смотрите инструкции к вашему дистрибутиву, например [Ubuntu](https://www.digitalocean.com/community/tutorials/how-to-set-up-timezone-and-ntp-synchronization-on-ubuntu-14-04-quickstart), [CentOS](https://www.vultr.com/docs/setup-timezone-and-ntp-on-centos-6) или [Amazon](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html) Linux). Многочисленные распределенные системы зависят от времени для синхронизации и координации, а UTC [предоставляет](https://blog.serverdensity.com/set-your-server-timezone-to-utc/) универсальную базовую плоскость: она не зависит от сезонных изменений времени и изменений локального времени. Это также избавит вас от головной боли при отладке [проблем с часовыми поясами](http://yellerapp.com/posts/2015-01-12-the-worst-server-setup-you-can-make.html) и предоставит вам согласованную временную шкалу событий в ваших системах логирования и аудита событий. \n-\t**NTP и точное время:** Если вы не используете Amazon Linux (который поставляется предварительно сконфигурированным), вы должны быть уверены что [сконфигурировали NTP на серверах правильно](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html#configure_ntp), чтобы избежать расхождения времени (что может вызвать всевозможные проблемы, от прерывания вызовов API до вводящих в заблуждение записях в лог-файлах). Это должно быть частью автоматической настройки для каждого сервера. Если же расхождение времени в значительной степени (обычно >1000 секунд) уже произошло, помните, что NTP не вернет его назад, так что вам придется перевести его вручную (например, [вот так](http://askubuntu.com/questions/254826/how-to-force-a-clock-update-using-ntp) на Ubuntu).\n-\t**Тестирование неизменной инфраструктуры:** Если вы хотите проактивно тестировать способность ваших сервисов справляться с внезапным отказом или падением инстансов, было бы полезным производить падение случайного инстанса в рабочее время, что поможет выявить любые подобные проблемы в то время, когда инженера доступны для идентификации и решения проблем. [Simian Army от Netflix](https://github.com/Netflix/SimianArmy) (в особенности, [Chaos Monkey](https://github.com/Netflix/SimianArmy/wiki/Chaos-Monkey)) очень популярный инструмент подобного рода. Альтернативным вариантом является [chaos-lambda](https://github.com/bbc/chaos-lambda) от BBC - это легковесный инструмент работающий на AWS [Lambda](#lambda).\n\nБезопасность и IAM\n----------------\n\nСначала мы рассмотрим основы безопасности, так как настройка учетных записей пользователей - это то, что вы обычно должны делать на ранних этапах настройки системы.\n\n### Основы безопасности и IAM\n\n-\t📒 IAM [Домашняя страница](https://aws.amazon.com/iam/) ∙ [Руководство пользователя](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) ∙ [ЧаВо](https://aws.amazon.com/iam/faqs/)\n-\t[Блог **Безопасность в AWS**](https://blogs.aws.amazon.com/security) - один из лучших источников новостей и информации о безопасности в AWS.\n-\t**IAM** - сервис управления учетными записями и разрешениями в AWS.\n-\tУправление безопасностью и контроль доступа в AWS является крайне критичным, поэтому каждый администратор AWS должен использовать и понимать IAM, по крайней мере, на базовом уровне.\n-\t[Учетные записи в IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html) включают пользователей (людей или сервисы, использующие AWS), группы (контейнера для наборов пользователей и их разрешений) и роли (контейнера для разрешений назначенных для сервисных инстансов AWS). [Разрешения](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_permissions.html) для этих учетных записей управляются [политиками](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html). Вы можете использовать предустановленные AWS политики или собственные политики, которые вы можете создать самостоятельно.\n-\tIAM управляет различными видами аутентификации как для пользователей, так и для программных сервисов, которым может потребоваться аутентификация с помощью AWS, включая:\n\t-\t[**Пароли**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords.html) для входа в консоль. Они представляют из себя пары имя пользователя - пароль для реальных пользователей.\n\t-\t[**Ключи доступа**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html), которые вы можете использовать для инструментов, использующих интерфейс командной строки. Это две строки, одна из которых “идентификатор”, состоящая из заглавных букв строка типа 'AXXXXXXXXXXXXXXXXXXX', а вторая - секрет, состоящая из 40 знаков разно-регистровая строка формата base64. Обычно они устанавливаются для сервисов, а не только для пользователей.\n\t\t-\t📜 Ключи, которые начинаются с AKIA - обычные. Ключи, которые начинаются с ASIA - временные/сессионные ключи из STS, и требуют дополнительного параметра \"SessionToken\" помимо идентификатора и секрета. Более подробно в документации сказано [о полном списке префиксов ключей доступа](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-prefixes).\n\t-\t[**Мульти-факторная аутенфикация (MFA)**](https://aws.amazon.com/iam/details/mfa/), - настоятельно рекомендуемая практика использования брелка с токеном или приложения на смартфоне в качестве второго уровня защиты для аутентификации пользователя.\n-\tIAM позволяет осуществлять сложный и детальный(гранулярный) контроль над разрешениями, разделять пользователей на группы, назначать разрешения ролям и т. д. Существует [язык политик](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html), который позволяет кастомизировать политики в целях осуществления детального(гранулярного) контроля.\n\t-\tОтличный общий обзор концепций политики IAM - [Политики IAM в двух словах](http://start.jcolemorrison.com/aws-iam-policies-in-a-nutshell/).\n\t-\t🔸Язык описания политик имеет довольно сложный и подверженный ошибка синтаксис JSON, что может привести к путанице, поэтому, пока вы не эксперт, разумным выбором является использование авторитетных примеров или предустановленных политик [управляемых AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html).\n-\tС начала, политики IAM могут показаться простыми, но с ростом систем, политики также будут усложняться и должны управляться с осторожностью.\n\t-\t🔹Убедитесь, что одному человеку (возможно, с замещающим человеком) в вашей организации официально поручено управление политиками IAM, а также чтобы каждый администратор работал с этим человеком для проверки изменений. Это имеет большое значение для предотвращения случайных ошибок в настройках, которые могут повлечь серьезные последствия.\n-\tЛучшей практикой является выдача пользователям и сервисам тех минимальных привилегий и разрешений, которые необходимы им для выполнения их задач. [Принцип минимальных привилегий](https://en.wikipedia.org/wiki/Principle_of_least_privilege) - одна из основ качественного обеспечения безопасности. Организуйте всех пользователей и группы IAM в соответствии с необходимыми уровнями доступа.\n-\tIAM использует [иерархию разрешений](http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html), включая:\n\t1. Явный запрет: Наиболее ограничивающая политика имеет высший приоритет.\n\t2. Явное разрешение: Разрешения доступа к любому ресурсу должны быть явно выданы.\n\t3. Неявный запрет: Все, что явно не разрешено - запрещено по умолчанию.\n-\tВы можете тестировать политики разрешений с использованием инструмента [симулятора политик AWS IAM](https://policysim.aws.amazon.com/home/index.jsp). Это в особенности полезно, когда вы пишите собственные политики. \n\n\n### Советы по безопасности и IAM\n\n-\t🔹Используйте IAM для создания индивидуальных пользовательских учетных записей **с самого начала используйте учетные записи IAM для всех пользователей**. Это займет какое-то количество трудозатрат, но не особо большое.\n\t-\tТаким образом, вы определяете разных пользователей и группы с разными уровнями привилегий (если хотите, выбирайте из предложенных  Amazon по умолчанию, администратора, опытного пользователя и т.д.).\n\t-\tЭто позволяет производить отзыв учетных записей, что может быть критичным в некоторых ситуациях. Если сотрудник увольняется или ключи скомпроментированы, вы можете отозвать учетные записи с небольшими усилиями. \n\t-\tВы можете использовать [службу федерации Active Directory](https://blogs.aws.amazon.com/security/post/Tx71TWXXJ3UI14/Enabling-Federation-to-AWS-using-Windows-Active-Directory-ADFS-and-SAML-2-0) для использования учетных записей вашей организации в AWS.\n-\t❗**Включите Мульти-факторную аутенфикацию [MFA](https://aws.amazon.com/iam/details/mfa/)** в настройках вашей учетной записи.\n\t-\tВам следует всегда использовать мульти-факторную аутенфикацию(MFA) и чем раньше - тем лучше, чем больше пользователей будет, тем больше времени это займет.\n\t-\tУвы, принудительное включение не может быть произведено в программном обеспечении, так что вам придется создавать административную политику.\n\t-\tБольшинство пользователей может использовать Google Authenticator (на [iOS](https://itunes.apple.com/us/app/google-authenticator/id388497605) или [Android](https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2)) для двух-факторной аутентификации. Для основной(root) учетной записи, стоило бы приобрести устройство в виде брелка, который генерирует токены.\n- \t❗Максимально ограничьте использование привилигерованных учетных данных IAM. Помните, что в облаке потеря привилигированных учетных данных IAM может, по существу, означать «игра окончена» для ваших развертываний, ваших пользователей или всей вашей компании.\n  -\t**НЕ ИСПОЛЬЗУЙТЕ [основную(Root) учетную запись](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html)** в любых других ситуациях, кроме первичного создания своей учетной записи.  Создайте учетные записи IAM для пользователей и/или IAM роли для ваших приложений.\n\t- Максимально ограничьте доступ и возможность использования основной(Root) учетной записи. В идеале она всегда должна быть в оффлайне. В случае крайней необходимости ее использования, она должна быть привязана к физическому устройству мультифакторной аутенфикации, храниться в оффлайне в защищенном месте и использоваться крайне редко.\n-\t❗**Включите CloudTrail:** Одним из первых дел, которые вы должны сделать - [включить CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-create-a-trail-using-the-console-first-time.html). Даже если вы не повернуты на безопасности, нет никаких причин не делать этого с самого начала, таким образом у вас всегда будет информация о том, что происходит у вас в AWS, а вам это точно пригодится. Кроме того, вы можете также захотеть поставить какой-нибудь [сервис управления лог-файлами](#видимость) для поиска событий и доступа к этим лог-файлам.\n-\t🔹**Используйте IAM роли для EC2:** Вместо того, чтобы создавать учетные записи пользователей в IAM и потом вставлять чувствительные данные типа логин/пароль в конфигурацию приложения, лучше стоит [определить и назначить роли EC2 инстансов](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) таким образом приложения будут получать данные из [метаданных инстанса](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html).\n-\tНазначьте роли IAM по областям применения - например, для разработки, стейджинга и эксплуатации. Если вы настраиваете роль, она должна быть привязана к определенной области, чтобы у вас было четкое разделение прав доступа. Это позволит избежать таких случаев, когда например система в разработке цепляется к боевой базе данных. \n-\t**Лучшие практики:** [Список лучших практик AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) стоит того, чтобы прочитать его в полном объеме.\n-\t**Справочник по IAM:** [Этот интерактивный справочник по действиям IAM, эффектам и ресурсам](https://iam.cloudonaut.io/) было бы прекрасно иметь под рукой, когда начинаешь писать новые или пытаешься понять существующие политики IAM.\n-\t**Использование нескольких учетных записей AWS:** Решите, необходимо ли вам использование нескольких учетных записей AWS и [изучите](https://dab35129f0361dca3159-2fe04d8054667ffada6c4002813eccf0.ssl.cf1.rackcdn.com/downloads/pdfs/Rackspace%20Best%20Practices%20for%20AWS%20-%20Identity%20Managment%20-%20Billing%20-%20Auditing.pdf) как организовать доступ между ними. Факторы к рассмотрению:\n\t-\tКоличество пользователей\n\t-\tВажность изоляции\n\t\t-\tЛимиты ресурсов\n\t\t-\tДетальность разрешений(гранулярность)\n\t\t-\tБезопасность\n\t\t-\tЛимиты API\n\t-\tНормативные вопросы\n\t-\tРабочие нагрузки\n\t-\tРазмер инфраструктуры\n\t-\t“Добавленная стоимость” использования нескольких учетных записей: Внутренние Внутренние инструменты управления сервисами AWS могут нуждаться в индивидуальной сборке или адаптации.\n\t-\t🔹Имеет смысл использовать раздельные учетные записи AWS для независимых частей вашей инфраструктуры, если вы планируете большую частоту вызовов AWS API, так как AWS [троттлит(пропускает) вызовы](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html#api-request-rate) на уровне учетной записи AWS.\n-\t[**Inspector**](https://aws.amazon.com/inspector/) - сервис автоматической оценки безопасности от AWS, помогающий выявить общие угрозы безопасности. Этот сервис позволяет проверить, что вы придерживаетесь определенных мер безопасности и может помочь с соблюдением требований регуляторов и стандартов.\n-\t[**Trusted Advisor**](https://aws.amazon.com/blogs/aws/trusted-advisor-console-basic/) проверяет соотвествие различным лучшим практикам, кроме того предлагает некоторые проверки безопасности, в основном использования IAM, конфигурации групп безопасностии использования мультифакторной аутенфикации(MFA). При использовании уровней платной поддержки, Trusted Advisor также раскрывает результаты дополнительных проверок относительно других областей, как например оптмизацию использования зарезервированных инстансов. \n-\t**Используйте KMS для управления ключами**: AWS предлагает [KMS](#kms) для защищенного управления ключами шифрования, что обычно является более лучшим варииантом, нежели самостоятельное обеспечение безопасности ключей. Смотрите [ниже](#kms).\n-\t[**AWS WAF**](https://aws.amazon.com/waf) - это файрвол веб-приложений, позволяющий вам защитить ваши приложения от стандартных атак.\n-\t**Аудит безопасности:**\n\t-\t[Security Monkey](https://github.com/Netflix/security_monkey) это инструмент с открытым исходным кодом, предназначенный для помощи при проведении аудита безопасности.\n\t-\t[Scout2](https://github.com/nccgroup/Scout2) это инструмент с открытым исходным кодом, использующий AWS API для оценки состояния безопасности среды. Scout2 стабилен и активно поддерживается.\n\t-\t🔹**Экспорт и настройки аудита безопасности:** Вы можете проверить политики безопасности, просто экспортировав настройки через AWS API, например используя Boto скрипт, вроде [SecConfig.py](https://gist.github.com/jlevy/cce1b44fc24f94599d0a4b3e613cc15d) (с вот [этого доклада 2013 года](http://www.slideshare.net/AmazonWebServices/intrusion-detection-in-the-cloud-sec402-aws-reinvent-2013)) и затем пересмотреть их и в последующем мониторить изменения вручную или автоматически.\n\n### Ошибки и ограничения в вопросе обеспечения безопасности и IAM\n\n-\t❗**Не делитесь учетными данными пользователей:** Замечательно возможностью для новичков в AWS является создание одной учетной записи и одного набора учетных данных (ключ доступа или пароль), и затем использовать их какое-то время, распространяя среди инженеров, да и вообще всех в компании. Это легко. Но *не делайте этого*. Это небезопасная практика по многим причинам, но, в частности, если вы это сделаете, у вас будет меньше возможностей для отзыва учетных данных для каждого пользователя или для каждого сервиса (например если работник уволился или ключ скомпроментирован), что может привести к серьезным проблемам.\n-\t❗**Троттлинг(пропуск) метаданных инстанса:** [Сервис метаданных инстанса](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) имеет определенное ограничение по частоте вызовов API. И если вы широко используете роли IAM (как и должны!) и у вас много сервисов, вы с легкостью достигнете глобальных ограничений на учетную запись.\n\t-\tОдним из решений является написание скриптов кэширующих и заново использующих учетные данные локально на короткий период (скажем 2 минуты). Например, они могут быть прописаны в файл ~/.aws/credentials, но также должны обновляться автоматически.\n\tНо будьте осторожны, чтобы не кэшировать учетные данные слишком долго, так как [они истекают](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials). (Обратите внимание, что [динамические метаданные](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#dynamic-data-categories) также меняются с течением времени и не должны быть закэшированы в течении долгого времени.)\n-\t🔸Некоторые операции IAM медленнее чем API вызовы других сервисов (несколько секунд), ввиду того, что AWS необходимо распространить их глобально на все регионы.\n-\t❗Время работы API IAM исторически было ниже, нежели API метаданных инстанса. Остерегайтесь включения зависимости от API IAM в критичные части или подсистемы, например если вы производите валидацию членства пользователя в группе IAM, при этом не обращаете внимания на возможность прекэширования членства в группе или возможное существование бэкдора, может произойти ситуация, когда вы перестанете блокировать любых пользователей, когда API недоступен.\n-\t❗**Не вносите учетные данные и, тем более, секреты в git репозитории.** Существуют автоматические боты, сканирующие GitHub в поисках учетных данных. Используйте скрипты или инструменты, такие как [git-secrets](https://github.com/awslabs/git-secrets) для предотвращения того, что кто-либо из вашей команды внесет чувствительную информацию в ваш git репозиторий.\n\nS3\n--\n\n### Основы S3\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/s3/) ∙ [Руководство разработчика](https://docs.aws.amazon.com/AmazonS3/latest/dev/Welcome.html) ∙ [ЧаВо](https://aws.amazon.com/s3/faqs/) ∙ [Расценки](https://aws.amazon.com/s3/pricing/)\n-\t**S3** (Простой сервис хранения(Simple Storage Service)) это стандартный облачный сервис хранения данных AWS, предлагающий файловое (скорее “blob”) хранилище произвольного количества файлов любого размера от 0 до **5TB**. (До [2011 года](https://aws.amazon.com/releasenotes/Amazon-S3/1917932037969964) максимальный размер файла был 5 GB; большие файлы на текущий момент отлично поддерживаются посредством использования [поддержки разбиения на несколько частей](https://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html).)\n-\tФайлы или **объекты** помещаются в именованные **бакеты(buckets)** и хранятся под именами, также называемыми **ключами**. Основное содержимое - **значение**.\n-\tОбъекты создаются, удаляются или обновляются. Большие объекты могут быть потоковыми, но вы не можете изменять части значения; вам нужно обновить весь объект. Частичный доступ может работать через [S3 Select](https://aws.amazon.com/blogs/aws/s3-glacier-select/).\n-\tУ каждого объекта есть [**метаданные**](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html), которые включают в себя произвольные пары ключ-значение и используются аналогично заголовкам HTTP. Некоторые метаданные определяются системой, некоторые имеют значение при передаче HTTP-содержимого из контейнеров или CloudFront, вы также можете определить произвольные метаданные для своего собственного использования.\n-\t**S3 URI:** Хотя часто имена бакетов и ключей предоставляются в API-интерфейсах по отдельности, обычной практикой является написание местоположения S3 в форме 's3://имя-бакета/путь/к/ключу' (где ключ и есть 'путь/к/ключу'). (Вам также встретятся префиксы 's3n://' и 's3a://' [в системах Hadoop](https://cwiki.apache.org/confluence/display/HADOOP2/AmazonS3).)\n-\t**S3 и Glacier, EBS, EFS:** AWS предлагает несколько сервисов хранения данных, и некоторые, помимо S3, предлагают абстракцию файловой системы. [Glacier](#glacier) - это дешевое хранилище для архивирования и редкого доступа. [EBS](#ebs), в отличие от S3, позволяет произвольный доступ к содержимому файлов посредством традиционной файловой системы, но может быть одновременно подключен только к одному инстансу EC2. [EFS](#efs) - это сетевая файловая система, к которой может подключиться несколько инстансов, но стоит дороже. Смотрите [сравнительную таблицу](#долговечность-и-надежность-хранения-доступность-и-цена).\n\n### Советы по S3\n\n-\tДля большинства практических целей можно считать емкость S3 неограниченной, как в общем размере файлов, так и по количеству объектов. Количество объектов в бакете также неограничено. Пользователи обычно имеют миллионы объектов. \n-   ❗**Разрешения:**\n    -   🔸Если вы храните бизнес-данные в Amazon S3, важно разумно управлять разрешениями. В 2017 году у компаний вроде[Dow Jones и Verizon](http://www.techrepublic.com/article/massive-amazon-s3-breaches-highlight-blind-spots-in-enterprise-race-to-the-cloud/) были утечки данных из-за слабо-настроенных конфигураций S3 для чувствительных данных. Исправление этого впоследствии может быть сложной задачей, если у вас множество файлов и внутренних пользователей.\n    -   🔸Существует три подхода выдачи разрешений на доступ к контенту в ваших бакетах Amazon S3.\n        + **Политики IAM** используют знакомую схему разрешений [IAM](#безопасность-и-iam) для контроля доступа к определенным операциям.\n        + **Политики бакета** позволяют выдавать разрешающие или запрещающие разрешения на весь бакет. Вы можете использовать их, когда размещаете веб-сайт в S3 для того, чтобы сделать бакет доступным общественности или запретить доступ к бакету по IP адресу. Amazon's [Примеры политик бакетов](http://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html) Amazon показывают несколько вариантов использования, когда эти политики могут вам пригодиться.\n        + **[Списки контроля доступа(Access Control Lists)](http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html)** (ACL) могут быть применены к любому бакету и объекту, хранимому в S3. ACL предоставляют дополнительные разрешения помимом тех, которые описаны в политике бакета или IAM. ACL могут быть использованы для предоставления доступа другому пользователю AWS или преопределенной группе, например широкой общественности. Это мощный инструмент, но он может быть опасным потому, что вам необходимо проверить каждый объект, чтобы увидеть, кто имеет доступ к нему.\n    -   🔸[Предопределенные группы контроля доступа AWS](http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#specifying-grantee-predefined-groups) разрешают доступ, который может быть не тем, что вы могли ожидать, исходя из их названия:\n        +   **\"Все пользователи\" или \"Все\" предоставляет разрешения широкой публике**, а не только пользователям описанным в вашем аккаунте AWS. Если объект доступен Всем Пользователям, значит, что он может быть получен простым HTTP запросом вида `http://s3.amazonaws.com/bucket-name/filename`. Никакой авторизации или подписи не требуется для доступа данных в этой категории.\n        +   **\"Аутентифицированные пользователи\" предоставляет разрешения любому с аккаунтом AWS**, опять же не ограничиваясь вашими личными пользователями. Так как каждый может зарегистрироваться в AWS, для любым целей и намерений, считайте, что **это тоже открыто для широкой публики**.\n        +   **Группа \"Доставка логов\" используется AWS, чтобы писать логи в бакеты** и это вполне безопасно включать эту опцию на бакетах, для которых это необходимо.\n        +   Обычным случаем использования данного ACL является использование в совокупности с функциональностью S3 [запрашивающий платит](http://docs.aws.amazon.com/AmazonS3/latest/dev/RequesterPaysBuckets.html).\n    -   ❗ Разрешения бакета и разрешения объекта - две разные вещи, независимые друг от друга. Приватный объект в публичном бакете может быть виден в процессе просмотра бакета, но не может быть скачан. В то же время, публичный объект в приватном бакете не может быть увиден, потому что содержимое приватного бакета не может быть просмотрено, однако может быть скачан любым, кто знает его точный ключ. Пользователи, у которых нет доступа к установке разрешений бакета, все еще могут устанавливать публичные разрешения на объект если у них есть доступ к `s3:PutObjectAcl` и `s3:PutObjectVersionAcl` [разрешениям](http://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html).\n    -   🐥В августе 2017 года, AWS добавил [правила AWS Config для того, чтобы вы могли убедиться, что ваши бакеты S3 защищены](https://aws.amazon.com/blogs/aws/aws-config-update-new-managed-rules-to-secure-s3-buckets/).\n        +    ❗Эти правила AWS Config проверяют только безопасность вашей политики бакетов и ACL на уровне бакетов. Вы по-прежнему можете создавать объектные ACL, которые предоставляют дополнительные разрешения, включая открытие файлов для всего мира.\n    -   🔹Создавайте новые бакеты, если у вас есть различные типы данных, с различной степенью критичности. Это намного проще и имеет меньшую вероятность допуска ошибок, нежели создание сложных правил и наборов разрешений. Как пример, если у вас есть данные только для администраторов, например логи, сложите их в новый бакет, к которому имеют доступ только администраторы.\n    -   Для получения дополнительной информации смотрите:\n        +   [Как обезопасить бакет Amazon S3](https://read.acloud.guru/how-to-secure-an-s3-bucket-7e2dbd34e81b)\n        +   [Глубокое погружение в контроль доступа в S3](https://labs.detectify.com/2017/07/13/a-deep-dive-into-aws-s3-access-controls-taking-full-control-over-your-assets/).\n        +   [Как работают разрешения S3?](https://brandonwamboldt.ca/understanding-s3-permissions-1662/).\n-\t**Именование бакетов:** Бакеты создаются в глобальном пространстве имен (во всех регионах, даже если сам S3 хранит данные [в любом регионе, который бы вы не выбрали](https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region), так что вы обнаружите, что множество имен для бакета уже выбрано. Создание бакета означает, что вы становитесь владельцем конкретного имени до тех пор пока не удалите его. Имена бакетов имеют [несколько ограничений](https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html).\n\t-\tИмена бакетов могут быть использованы как часть имени хоста, когда вы получаете доступ к бакету или его содержимому, вроде `<bucket_name>.s3-us-east-1.amazonaws.com`, до тех пор пока имя соответствует стандарту [DNS имен](http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html).\n\t-\tОбычной практикой является использование аббревиатуры или сокращения названия компании в качестве префикса (или суффикса, если вы предпочитаете иерархию в стиле DNS) для всех имен бакетов (но, пожалуйста, не используйте проверку этого в качестве меры безопасности - это крайне небезопасно и легко обойти!).\n\t-\t🔸Имена бакетов с '.' (точками) в них [может привести к несоответствию сертификатов](https://forums.aws.amazon.com/thread.jspa?threadID=169951), когда используется с SSL. Используйте '-' вместо этого, так как символ соответствует требованиям, как SSL, так и DNS.\n-\t**Версионность:** S3 имеет [опциональную поддержку версионности](https://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectVersioning.html), так что все версии объектов сохраняются в бакете. Это очень полезно, если вы хотите архивировать изменения и иметь возможность откатить ошибки (предупреждение: в нем отсутствует набор функций полноценных систем контроля версий, таких как Git).\n-\t**Сохранность:** Сохранность данных в S3 экстремально высока, так как внутренне он сохраняет несколько реплик. Если вы случайно не удалили данные, вы можете расчитывать на то, что S3 не потеряет ваши данные. (AWS предлагает невероятный уровень сохранности данных - [99.999999999%](https://aws.amazon.com/s3/faqs/#How_durable_is_Amazon_S3), но это математический расчет основан на уровне независимых отказов и уровнях репликации, так что не он не являяется оценкой реальной вероятности. В любом случае у S3 [хорошие показатели](https://www.quora.com/Has-Amazon-S3-ever-lost-data-permanently) сохранности данных.) Имейте ввиду, что S3 *имеет намного более высокий* уровень сохранности, чем EBS!\n-\t💸**Расценки S3** зависят от [типа хранилища, запросов и передачи данных](https://aws.amazon.com/s3/pricing/).\n\t-\tПередача данных в AWS бесплатна, но вы будете платить, когда передача данных будет с AWS. Передача с S3 на EC2 в *одном и том же регионе* бесплатна. Передача в другие регионы или в интернет в общем не является бесплатной.\n\t-\tУдаление бесплатно.\n-\t**S3 со сниженной отказоустойчивостью и нечастым доступом(S3 Reduced Redundancy and Infrequent Access):** Большинство людей использует класс стандартного хранения в S3, но существуют другие классы хранения с более низкой ценой:\n\t-\t🔸[Хранилище со сниженной отказоустойчивостью(Reduced Redundancy Storage (RRS))](https://aws.amazon.com/s3/reduced-redundancy/) фактически [устарело](https://www.lastweekinaws.com/blog/s3-reduced-redundancy-storage-is-dead/) и имело меньший уровень сохранности данных (99.99%, всего четыре девятки), нежели стандартный S3. Имейте ввиду, что он больше не рассматривается, как вариант снижения затрат на S3, так как он предлагает худшую отказоустойчивость за большие деньги, нежели стандартный S3. В результате, нет никаких причин использовать его.\n\t-\t[Редкий доступ(Infrequent Access (IA))](https://aws.amazon.com/s3/storage-classes/#Infrequent_Access) позволяет вам получить более дешевое хранение в обмен на более дорогой доступ. Это отличный вариант для архивных данных, таки как логи, которые вы уже обработали, но возможно захотите просмотреть позднее. Чтобы получить представление об экономии средств при использовании Infrequent Access (IA), вы можете использовать этот [калькулятор S3 Infrequent Access](http://www.gulamshakir.com/apps/s3calc/index.html).\n\t-\t[Интеллектуальное переключение уровней S3(S3 - Intelligent Tiering)](https://aws.amazon.com/about-aws/whats-new/2018/11/s3-intelligent-tiering/) - класс хранения предназначенный для оптимизации затрат за счет автоматического перемещения данных на самый экономически эффективный уровень доступа без ущерба для производительности или операционных издержек.\n\t-\t[Одна зона - нечастный доступ - S3(S3 - One Zone - IA)](https://aws.amazon.com/s3/storage-classes/#__) предназначен для данных, доступ к которым осуществляется реже, но при необходимости требуется быстрый доступ. В отличие от других классов хранения S3, которые хранят данные как минимум в трех зонах доступности (AZ), S3 One Zone-IA хранит данные в одном AZ и стоит на 20% дешевле, чем S3 Standard-IA.\n\t-\t[Glacier](#glacier) является отдельной альтернативой, обсуждаемой как отдельный продукт.\n\t-\tОзнакомьтесь со [сравнительной таблицей](#долговечность-и-надежность-хранения-доступность-и-цена).\n-\t⏱**Производительность:** Максимизация производительности S3 означает улучшение общей пропускной способности с точки зрения пропускной способности и количества операций в секунду.\n\t-\tS3 обладает высокой масштабируемостью, поэтому, в принципе, вы можете получить произвольно высокую пропускную способность. (Хороший пример - [S3DistCp](https://docs.aws.amazon.com/ElasticMapReduce/latest/ReleaseGuide/UsingEMR_s3distcp.html).)\n\t-\tОднако, обычно вы ограничены пропускной способностью канала между источником и S3 и/или уровнем параллелизма операций.\n\t-\tПропускная способность, конечно, самая высокая между AWS и S3(внутри AWS), а также между инстансами EC2 и бакетами S3, которые находятся в одном регионе.\n\t-\tПропускная способность с EC2 зависит от типа инстанса. Обратите внимание на столбец “Сетевая производительность(Network Performance)” на [ec2instances.info](http://www.ec2instances.info/).\n\t-\tПропускная способность чрезвычайно высока при распределенном доступе к данным с множества инстансов EC2. Можно читать или записывать объекты в S3 с сотен или тысяч инстансов одновременно.\n\t-\tТем не менее, пропускная способность очень ограничена, когда объекты запрашиваются последовательно с одного инстанса. Отдельные операции занимают много миллисекунд, а пропускная способность для инстансов ограничена.\n\t-\tТаким образом, для того, чтобы производить множество операций - необходимо использовать несколько рабочих потоков и соединений с отдельных иснстансов, а для еще более крупных задач - использовать множество инстансов EC2.\n\t-\t**Загрузка несколькими частями:** Для больших объектов вы можете воспользоваться удобством возможности загрузки несколькими чамтями (начиная с минимального куска данных размером в 5 MB).\n\t-\t**Большие скачивания:** Также вы можете скачать куски одного большого объекта параллельно, благодаря возможности использования заголовка HTTP GET range.\n\t-\t🔸**Разбиение списка по страницам:** Просмотр содержимого происходит путем получения 1000 ответов на запрос, таким образом для бакетов со многими миллионами объектов - просмотр займет долгое время.\n\t-\t❗**Префиксы ключей:** Ранее требовалась произвольная полсдеовательность в начале имени ключа, чтобы избежать горячих точек(снижения производительности), но теперь это [не является необходимым](https://aws.amazon.com/about-aws/whats-new/2018/07/amazon-s3-announces-increased-request-rate-performance/) по состоянию на июль 2018 года.\n\t-\tДля данных вне AWS, [**DirectConnect**](https://aws.amazon.com/directconnect/) и [**S3 Transfer Acceleration**](https://aws.amazon.com/blogs/aws/aws-storage-update-amazon-s3-transfer-acceleration-larger-snowballs-in-more-regions/) могут помочь. За использование S3 Transfer Acceleration, вы [платите](https://aws.amazon.com/s3/pricing/) примерно столько же, сколько за 1-2 месяца хранения, за передачу в любом направлении при использовании ближайших входных точек.\n-\t**Приложения для коммандной строки:** Существует несколько путей использования S3 из командной строки:\n\t-\tИзначально, [**s3cmd**](https://github.com/s3tools/s3cmd) был лучшим иструментом для этой задачи. И он до сих пор массово используется.\n\t-\tОбычный интерфейс командной строки [**aws**](https://aws.amazon.com/cli/) сейчас прекрасно поддерживает S3 и полезен в большинстве ситуаций.\n\t-\t[**s4cmd**](https://github.com/bloomreach/s4cmd) - это обновленная замена, с большим акцентом на производительности с использованием многопоточности, что может быть полезно при работе с крупными файлами или большими наборами файлов, а также имеет поддержку Unix-подобного глоббинга, то есть замены символов звездочкой и вопросительным знаком.\n-\t**Приложения с графическим интерфейсом(GUI applications):** Вы можете предпочитать работу с графическим интерфейсом, или вам необходима поддержка доступа через графический интерфейс для пользователей с меньшими техническими навыками. Вот несколько вариантов:\n\t-\t[Консоль AWS](https://aws.amazon.com/console/) предлагает графический вариант использования S3. С предосторожностью предоставляйте ее использование не техническому персоналу, так как, без жестких разрешений, посредством консоли предоставляется доступ ко многим другим ресурсам и функциям AWS.\n\t-\t[Transmit](https://panic.com/transmit/) хороший вариант на macOS для большинства случаев использования.\n\t-\t[Cyberduck](https://cyberduck.io/) хороший вариант на macOS и Windows с поддержкой загрузки по частям, списков контроля доступа, версионностью, конфигурацией жизненного цикла, классами хранения и шифрованием на стороне сервера (SSE-S3 и SSE-KMS).\n-\t**S3 и CloudFront:** S3 тесно интегрирован с CloudFront CDN. Ознакомьтесь с разделом посвященным CloudFront для получения подробной информации, также как и [S3 transfer acceleration](https://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html).\n-\t**Размещение статичных веб-сайтов:**\n\t-\tУ S3 есть [возможность размещения статичных веб-сайтов](http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html) которая является простой настройкой, которая включает настраиваемые страницы, начальную и страницу ошибки, а также имеет [поддержку перенаправления HTTP](http://docs.aws.amazon.com/AmazonS3/latest/dev/how-to-page-redirect.html) к [общедоступному содержимому](http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteAccessPermissionsReqd.html) в S3. Это крайне простой способ размещать статичные данные или полностью статичный веб-сайт.\n\t-\tРассмотрите возможность использования CloudFront для большинства или для всех данных:\n\t\t-\tКак любая сеть доставки контента, CloudFront серьезно повышает производительность.\n\t\t-\t🔸SSL поддерживается только для встроенного домена amazonaws.com в S3. S3 поддерживает обслуживания сайтов через [частные домены](http://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-custom-domain-walkthrough.html), однако [не поддерживает SSL на частных доменах](http://stackoverflow.com/questions/11201316/how-to-configure-ssl-for-amazon-s3-bucket). В любом случае, [CloudFront позволяет вам обслуживать частные домены через https](http://docs.aws.amazon.com/acm/latest/userguide/gs-cf.html). Amazon предоставляет бесплатные SSL/TLS сертификаты с поддержкой SNI посредством Amazon Certificate Manager. [SNI не работает на устаревших браузерах/операционных системах](https://en.wikipedia.org/wiki/Server_Name_Indication#Support). В любом случае, вы можете предоставить свой собственный сертификат для использования в CloudFront для поддержки всех браузеров/операционных систем, но за плату.\n\t\t-\t🔸Если вы используете ресурсы с разных доменов, как например шрифты, внутри ваших файлов CSS, вам может быть необходимо [настроить CORS](https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html) для бакетов, обслуживающих эти ресурсы.\n\t\t-\tПоскольку в настоящее время практически все переходит на SSL и вам, вероятно, нужен контроль над доменом, вы, вероятно, захотите настроить CloudFront со своим собственным сертификатом для S3 (и проигнорировать [этот пример от AWS ](http://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-custom-domain-walkthrough.html) так как он не без SSL).\n\t\t-\tТем не менее, если вы это сделаете, вам нужно продумать инвалидацию файлов или обновления CloudFront. Возможно вы пожелаете [включить версии или хэши в именах файлов](https://abhishek-tiwari.com/CloudFront-design-patterns-and-best-practices), таким образом инвалидация не потребуется.\n-\t**Жизненные циклы данных:**\n\t-\tПри управлении данными понимание жизненного цикла данных так же важно, как и понимание самих данных. Когда вы помещаете данные в бакет, подумайте об их жизненном цикле - окончании, а не только начале.\n\t-\t🔹Как правило, данные с разными политиками истечения срока действия должны храниться под отдельными префиксами в начале. Например, некоторые объемные лог файлы должны автоматически удаляться ежемесячно, в то время, как другие данные критичны и никогда не должны удаляться. Хранение ранних данных в отдельном бакете или в отдельной папке - весьма разумно. \n\t-\t🔸Если подумать об этом заранее - это поможет избежать многих проблем в будущем. Очень сложно чистить большие наборы файлов созданные многими инженерами с разными жизненными циклами и отсутствием какой-либо цельной организации.\n\t-\tТакже вы можете настроить политику жизненного цикла для архивации старых данных в Glacier. [Будьте аккуратны](https://alestic.com/2012/12/s3-glacier-costs/) при архивации большого количества маленьких объектов в Glacier, так как это может стоить еще дороже.\n\t-\tТакже существует класс хранения, называемый [**Нечастый доступ(Infrequent Access)**](https://aws.amazon.com/s3/storage-classes/#Infrequent_Access) который имеет тот же уровень сохранности данных, как и стандартный S3, но стоит дешевле за GB. Он подходит для объектов, к которым редко обращаются.\n-\t**Согласованность данных:** Понимание [согласованности данных](https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyModel) крайне важно для любого использования S3, так как тут есть несколько производителей и потребителей данных.\n\t-\tСоздание и обновление индивидуальных объектов в S3 **атомарное(atomic)**, таким образом у вас никогда не будет ситуации, что вы обновляете иил загружаете новый объект, а другой клиент видит только часть изменений. \n\t- Неопределенность заключается в том, *когда* вы и ваши клиенты увидят обновления.\n\t-\t**Новые объекты:** Если вы создаете новый объект, вы сможете немедленно его прочитать, что называется **согласованность чтения-после-записи(read-after-write consistency)**.\n\t\t-\tК слову, дополнительно необходимо предупредить, что если вы пытаетесь прочесть объект до его создания, а потом создаете его [вы получаете возможную согласованность](https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyModel) (не чтения-после-записи).\n\t\t-\tЭто не относится к операциям просмотра; впервые созданные объекты [не гарантированно сразу появятся при операциях просмотра содержимого бакетов](https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyModel)\n\t-\t**Обновления объектов:** Если вы перезаписываете или удаляете объект, вы получаете только гарантированную **возможноую согласованность(eventual consistency)**, то есть изменение будет применено, но нет никаких гарантий когда.\n\t- 🔹Для большинства случаев использования, принятие решения об использовании объектов S3, как **неизменных** (то есть предварительно приняв решение, что объекты будут либо создаваться, либо удаляться, но не обновляться) может крайне сильно упростить код, использующий объекты, путем исключения сложного управления состоянием объектов.\n\t-\t🔹Имейте ввиду, что [до 2015 года](https://aws.amazon.com/about-aws/whats-new/2015/08/amazon-s3-introduces-new-usability-enhancements/), регион'us-standard' имел более слабую модель возможной согласованности, а другие (более новые) регионы могли считывать после записи. Это наконец-то было исправлено - но вы можете почитать множество старых блогов, рассказывающих об этом.\n\t-\t**Медленные обновления:** На практике, “возможная согласованность” обычно означает получение результата через секунд, за исключением редких случаев, когда согласованность возникает через минуты или даже [часы](http://www.stackdriver.com/eventual-consistency-really-eventual/).\n-\t**S3 как файловая система:**\n\t-\tВ общем, API S3 имеет внутренние ограничения, которые делают сложным использование S3 в качестве POSIX-подобной файловой системы, при сохранении собственного объектного формата S3. Как пример, добавление данных в файл требует перезаписи, что крайне сильно снижает производительность, кроме того, невозможно атомарное переименование директорий, взаимное изолирование при работе с файлами и жесткие ссылки также не поддерживаются.\n\t-\t[s3fs](https://github.com/s3fs-fuse/s3fs-fuse) это файловая система типа FUSE(filesystem in user environment - файловая система в пользовательском окружении) которая продолжает развитие и, несмотря ни на что, продолжает попытки улучшения, но имеет ограничения производительности и посему удивляет, что вообще поддерживается.\n\t-\t[Riofs](https://github.com/skoobe/riofs) (на C) и [Goofys](https://github.com/kahing/goofys) (на Go) являются более поздними усилиями применить другой формат хранения данных в целях решения подобных проблем, и похоже являются улучшениями s3fs.\n\t-\t[S3QL](https://github.com/s3ql/s3ql) ([обсуждение](https://news.ycombinator.com/item?id=10150684)) это реализация на Python, которая предлагает поддержку дедупликации данных, мгновенных снимков(снапшотов) и шифрование, но имеет ограничение на одновременное использование только одним пользователем.\n\t-\t[ObjectiveFS](https://objectivefs.com/) ([обсуждение](https://news.ycombinator.com/item?id=10117506)) это коммерческое решение, которое поддерживает функционал файловой системы и конкурентные подключения.\n-\tЕсли вы изначально используете VPC, рассмотрите возможность установки [выходной точки VPC(VPC Endpoint)](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-endpoints.html) для S3 в целях обеспечения возможности ресурсов размещенных в VPC легко получать доступ в S3 без дополнительных сетевых настроек или дополнительных узлов.\n-\t**Межрегиональная репликация:** S3 имеет [возможность](https://docs.aws.amazon.com/AmazonS3/latest/dev/crr.html) репликации бакетов между регионами. Имейте ввиду, что S3 итак сильно реплицируется внутри одного региона, так что это обычно не является необходимым для сохранности данных, однако это может быть необходимо для соответствия правилам и стандартам (географически распределенное хранение даннных), снижения задержек или как стратегия по снижению затрат на передачу даннных между регионами путем зеркалирования часто используемых данных во втором регионе. \n-\t**IPv4 и IPv6:** В течении долгого времени S3 поддерживал только IPv4 на стандартной выходной точке `https://BUCKET.s3.amazonaws.com`. Как бы там не было, [по состоянию на 11 августа 2016 года](https://aws.amazon.com/blogs/aws/now-available-ipv6-support-for-amazon-s3/) он теперь поддерживает как IPv4, так и IPv6! Чтобы использовать оба, вам необходимо [включить двойной стэк (dualstack)](http://docs.aws.amazon.com/AmazonS3/latest/dev/dual-stack-endpoints.html), либо используя предпочитаемый клиент API или напрямую, используя выходную точку `https://BUCKET.s3.dualstack.REGION.amazonaws.com`. Это также относится к S3 Transfer Acceleration.\n-\t**Оповещения о событиях S3:** S3 может быть настроен для отправки [оповещений SNS](https://aws.amazon.com/blogs/aws/introducing-the-amazon-simple-notification-service/), [сообщений в SQS](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/Welcome.html), или вызова [функции AWS Lambda](http://docs.aws.amazon.com/lambda/latest/dg/welcome.html) в ответ на [события бакетов](http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html).\n-   💸Ограничьте пользователям (или ролям IAM) доступ к только минимальным необходимым объектам и бакетам в S3, и ведите учет “разрешенных” путей. Иначе, S3 постепенно превращается в свалку, куда люди закидывают данные в различные расположения, которые потом годами не очищаются, что, в итоге, может обойтись очень дорого.\n- Если бакет удаляется из S3, может потребоваться до 10 часов, пока бакет с тем же именем может быть создан заново. ([обсуждение](https://forums.aws.amazon.com/thread.jspa?threadID=37532))\n\n### Ошибки и ограничения S3\n\n-   ❗Бакеты S3 находятся вне VPC и могут быть доступны с любого места в мире, если полтитики бакета не запрещают этого. Прочтите раздел о разрешениях тщательно, существует неисчислимое количество случаев, когда бакеты были случайно открыты широкой публике. \n-\t🔸В течении многих лет, существовал пресловутый лимит  [**в 100 бакетов**](https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_s3) на учетную запись,  который не мог быть увеличин, и доставлял много проблем многим компаниям. По состоянию на 2015 год, вы можете [запросить увеличение лимита](https://aws.amazon.com/about-aws/whats-new/2015/08/amazon-s3-introduces-new-usability-enhancements/). Вы можете запросить увеличение лимита, но он все равно будет ограничен (обычно меньше 1000 на учетную запись).\n-\t🔸Будьте аккуратны, чтобы не делать неявных предположений о транзакционности или последовательности обновлений объектов. Никогда не думайте, что если вы измените последовательность объектов, клиенты увидят одинаковые изменения в одной и той же последовательности или если вы загрузите целую кучу файлов, то все они появятся сразу для всех клиентов.\n-\t🔸У S3 есть [**SLA**](https://aws.amazon.com/s3/sla/) гарантирующее 99.9% времени работоспособности. Если вы интенсивно используете S3, вы неизбежно увидите случайную ошибку при доступе или хранении данных при сбое дисков или другой инфраструктуры. Доступность обычно восстанавливается за секунды или минуты. Хотя доступность не очень высока, как уже упоминалось выше, сохранность данных отличная.\n-\t🔸После загрузки, любое изменение объекта приводит к полной перезаписи объекта, поэтому старайтесь избегать операций добавления данных в файлы.\n-\t🔸Последовательная согласованность данных, как обсуждалось выше, иногда может удивлять. Если в S3 существуют проблемы внутренней репликации, объект может быть виден по разному с набора машин, в зависимости от того, на какую выходную точку S3 они обращаются. Эта проблема обычно разрешается за секунды, однако мы наблюдали отдельные случаи, когда проблема растягивалась на 20-30 часов.\n-\t🔸**MD5 и загрузка по частям:** В S3,  [заголовок ETag](http://docs.aws.amazon.com/AmazonS3/latest/API/RESTCommonResponseHeaders.html) является хэшем объекта. В большинстве случаев - это хэш MD5. В любом случае, это [в целом не так](http://stackoverflow.com/questions/12186993/what-is-the-algorithm-to-compute-the-amazon-s3-etag-for-a-file-larger-than-5gb) когда вы используете загрузку по частям. Одним из методов обхода - вычислить хэши MD5 самостоятельно и добавить их в отдельный заголовок (это может быть сделано с помощь [s4cmd](https://github.com/bloomreach/s4cmd)).\n-\t🔸**Затраты за незавершенную загрузку по частям:** Незавершенные загрузки по частям приводят к [затратам за хранение](http://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html#mpuploadpricing) даже в том случае, если загрузка оборвалась и объект S3 не был создан. [Amazon](http://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html#mpu-abort-incomplete-mpu-lifecycle-config) ([и](http://www.deplication.net/2016/06/aws-tip-save-s3-costs-with-abort.html) [другие](https://www.sumologic.com/aws/s3/s3-cost-optimization/)) рекомендуют использовать политики жизненного цикла, для очистки незавершенных загрузок и уменьшения затрат за храненеие данных. Имейте ввиду, что если у вас много таких случаев, возможно стоит разобраться почему загрузки часто обрываются.\n-\t🔸**Регион US Standard:** Ранее, регион us-east-1 (также известный, как регион US Standard) реплицировался между побережьями, что приводило к большой вариативности задержек. Начиная с 19 июня 2015 года [это уже не так](https://forums.aws.amazon.com/ann.jspa?annID=3112). Все регионы Amazon S3 теперь поддерживают согласованность данных чтение-после-записи. Amazon S3 также переименовал регион US Standard на US East (N. Virginia) чтобы соответствовать соглашению по именованию регионов AWS.\n- 🔸**Регионы и версии аутентификации S3:** В новых регионах S3 [поддерживает только последнюю версию аутентификации](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version). Если файловая операция S3 через CLI или SDK не работает в одном регионе, но работает правильно в другом регионе, убедитесь, что вы используете последнюю  [аутентификационную подпись](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html).\n\n### Долговечность и надежность хранения, доступность и цена\n\nВ качестве иллюстрации сравнительных характеристик и цены в таблице ниже приведены S3 Standard, RRS, IA по сравнению с [Glacier](#glacier), [EBS](#ebs), [EFS](#efs), и инстанс EC2 d2.xlarge в регионе **Virginia** по состоянию на **сентябрь 2017 года**.\n\n|                 | Сохранность данных (в год)  | Доступность “проектная” | Доступность согласно SLA | Цена за хранение (за TB в месяц)                                                                                               | GET или получение (за миллион) | Запись или архивация (за миллион) |\n|-----------------|------------------------|-------------------------|------------------|--------------------------------------------------------------------------------------------------------------------------|-------------------------------|--------------------------------|\n| **Glacier**     | Одиннадцать 9ок              | Мееедлеенно                 | –                | $4                                                                                                                       | $50                           | $50                            |\n| **S3 IA**       | Одиннадцать 9ок              | 99.9%                   | **99%**          | $12.50                                                                                                                   | $1                            | $10                            |\n| ~~**S3 RRS**~~      | ~~**99.99%**~~             | ~~99.99%~~                  | ~~99.9%~~            | ~~$24 (первый TB)~~                                                                                                                      | ~~$0.40~~                         | ~~$5~~                             |\n| **S3 Standard** | Одиннадцать 9ок              | 99.99%                  | 99.9%            | $23                                                                                                                     | $0.40                         | $5                             |\n| **EBS**         | **99.8%**              | Не определено                | 99.99%           | $25/$45/**$100**/$125+ ([sc1/st1/**gp2**/io1](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html)\\) |                               |                                |\n| **EFS**         | “Высокая”                 | “Высокая”                  | –                | $300                                                                                                                     |                               |                                |\n| **EC2 d2.xlarge instance store**  | Не определено | Не определено                | –                | $25.44                                                                                                                   | $0                            | $0                             |\n\nОсобенно важные момент выделены **жирным шрифтом**. Источники: [Расценки S3](https://aws.amazon.com/s3/pricing/), [S3 SLA](https://aws.amazon.com/s3/sla/), [S3 ЧаВо](https://aws.amazon.com/s3/faqs/), [информация об RRS ](https://aws.amazon.com/s3/reduced-redundancy/) (имейте ввиду, что он устарел), [Расценки Glacier](https://aws.amazon.com/glacier/pricing/), [Доступность EBS и сохранность данных](https://aws.amazon.com/ebs/details/#Amazon_EBS_Availability_and_Durability), [Расценки EBS](https://aws.amazon.com/ebs/pricing/), [Расценки EFS](https://aws.amazon.com/efs/pricing/), [EC2 SLA](https://aws.amazon.com/ec2/sla/)\n\nEC2\n---\n\n### Основы EC2 \n\n-\t📒 [Домашняя страница](https://aws.amazon.com/ec2/) ∙ [Документация](https://aws.amazon.com/documentation/ec2/) ∙ [ЧаВо](https://aws.amazon.com/ec2/faqs/) ∙ [Расценки](https://aws.amazon.com/ec2/pricing/) (также смотрите [ec2instances.info](http://www.ec2instances.info/)\\)\n-\t**EC2** (Elastic Compute Cloud) это предложение самого фундаментального компонента облачных вычислений от AWS: [виртуальный частный сервер](https://en.wikipedia.org/wiki/Virtual_private_server). На этих “инстансах” можно запускать [большинство операционных систем Linux, BSD и Windows](https://aws.amazon.com/ec2/faqs/#What_operating_system_environments_are_supported). Под капотом используется сильно модифицированная виртуализация [Xen](https://en.wikipedia.org/wiki/Xen). К слову, новые классы инстансов, использующие KVM производный гипервизор, названный [Nitro](http://www.brendangregg.com/blog/2017-11-29/aws-ec2-virtualization-2017.html), уже были представлены. На текущий момент, его использование ограничено типами инстансов C5 и M5. В заключение, существует \"bare metal\" гипервизор доступный на [i3.metal инстансах](https://aws.amazon.com/about-aws/whats-new/2018/05/announcing-general-availability-of-amazon-ec2-bare-metal-instances/)   \n-\tТермин “EC2” иногда используется для обозначения самих серверов, но технически относится и ко всей совокупности вспомогательных услуг, таких как балансировка нагрузки (CLB/ALB/NLB), IP-адреса (EIP), загрузочные образы (AMI), группы безопасности и сетевые диски (EBS) (которые мы обсудим отдельно в этом руководстве).\n-\t**💸[Расценки на EC2](https://aws.amazon.com/ec2/pricing/)** и **[управление затратами](#управление-затратами-на-ec2)** являются сложными темами. Они могут варьироваться с полностью бесплатных (во время использования [AWS free tier](https://aws.amazon.com/free/)) до больших денег, в зависимости от вашего использования. Расценки зависят от типа инстанса, тарифицируются посекундно или почасово, меняются в зависимости от региона и зависят от варианта покупки инстанса, как например, [По требованию](https://aws.amazon.com/ec2/pricing/on-demand/), на [Spot рынке](https://aws.amazon.com/ec2/spot/) или предзаказ ([зарезервированных инстансов](https://aws.amazon.com/ec2/pricing/reserved-instances/)).\n- **Производительность сети:** Для некоторых типов инстансов, AWS использует общие темы типа Малая, Средняя и Высокая в отношении сетевой производительности. Пользователи произвели [замеры](http://stackoverflow.com/questions/18507405/ec2-instance-typess-exact-network-performance) чтобы понять, что из себя представляют данные термины.\n\n### Альтернативы EC2 и привязки\n\n-\tЗапуск EC2 аналогичен запуску набора физических серверов, до тех пор пока вы не выполняете автоматическое масштабирование или слишком сложную настройку кластера. Если вы просто запускаете набор статических экземпляров, миграция на другой VPS или выделенный сервер не должна быть слишком сложной.\n-\t🚪**Альтернативы EC2:** Прямыми альтернативами являются Google Cloud, Microsoft Azure, Rackspace, DigitalOcean, собственное предложение AWS Lightsail и другие поставщики VPS, некоторые из которых предлагают аналогичные API для настройки и удаления инстансов. (Смотри сравнение [выше](#когда-использовать-aws).)\n-\t**Должны ли вы использовать Amazon Linux?** AWS поощряет использование их собственной операционной системы [Amazon Linux](https://aws.amazon.com/amazon-linux-ami/), которая эволюционировала из [Red Hat Enterprise Linux (RHEL)](https://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux) и [CentOS](https://en.wikipedia.org/wiki/CentOS). Она используется многими, но [есть и скептики](https://www.exratione.com/2014/08/do-not-use-amazon-linux/). Что бы вы не делали, обдумывайте решение тщательно. Это правда, что Amazon Linux тщательно протестирован и лучше поддерживается в маловероятном случае возникновения серьезных проблем с ОС и виртуализацией в EC2. Но в общем, многие компании вполне нормально используют стандартные, не-Amazon Linux дистрибутивы, такие как Ubuntu или CentOS. Использование стандартного дистрибутива Linux означает, что у вас аналогично воспроизводимая среда, если вы используете другого хостинг-провайдера вместо (или в дополнение к) AWS. Это также полезно, если вы хотите протестировать развертывания на локальных компьютерах разработчиков, работающих под управлением того же стандартного дистрибутива Linux (данная практика становится еще более распространенной с Docker. Amazon теперь поддерживает официальный [базовый образ Docker Amazon Linux ](http://docs.aws.amazon.com/AmazonECR/latest/userguide/amazon_linux_container_image.html), направленный на содействие локальной разработке в сопостовимой среде, хотя это пока все достаточно новое, так что может считаться экспериментальным). Имейте ввиду, что в данный момент тестируемый [Amazon Linux 2](https://aws.amazon.com/about-aws/whats-new/2017/12/introducing-amazon-linux-2/) поддерживает явное локальное развертывание.\n-\t**Расценки EC2:** Смотри [раздел об этом](#управление-затратами-на-ec2).\n\n### Советы по EC2\n\n-\t🔹**Выбор региона:** Когда вы начинаете использовать AWS, сначала определитесь какие [регионы](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) вы хотите использовать. Многие люди в Северной Америке автоматически выбирают регион us-east-1 (N. Virginia), который стоит по умолчанию, но стоит подумать заранее, идеально ли подходит он вашим требованиям. Вы явно захотите оценить доступность сервисов (некоторые сервисы [доступны не во всех регионах](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)), затраты (также [варьируются в зависимости от региона](https://aws.amazon.com/ec2/pricing/) до 10-30% (как правило самые низкие в us-east-1 для сравнения)), а также соотвествие нормативным требованиям (различные страны например, имеют различные правила в отношении конфиденциальности данных).\n-\t**Типы инстансов:** Инстансы EC2 бывают разных типов, в соответствии с возможностями виртуальной машины в архитектуре и скорости процессора, оперативной памяти, размерах и типах дисков (SSD или магнитных) и пропускной способности сети.\n\t-\tВыбор типа инстанса является сложным, поскольку существует очень много типов. Вдобавок существуют разные поколения, выпущеные [за долгие годы](https://aws.amazon.com/blogs/aws/ec2-instance-history/).\n\t-\t🔹Используйте список на сайте [**ec2instances.info**](http://www.ec2instances.info/) чтобы оценить затраты и особенности. [Собственный список типов инстансов Amazon](https://aws.amazon.com/ec2/instance-types/) сложно использовать, и там не указаны особенности и цены вместе, что делает его вдвойне сложным.\n\t-\tЦены сильно варьируются, поэтому используйте [**ec2instances.info**](http://www.ec2instances.info/) определить набор машин, которые отвечают вашим потребностям и [**ec2price.com**](http://ec2price.com/) чтобы найти самый дешевый тип в регионе, в котором вы работаете. В зависимости от времени работы и региона может оказаться гораздо дешевле арендовать инстанс с *большим* объемом памяти или ЦП, чем инстанс с минимальной конфигурацией.\n  - **Выключайте** ваши инстансы, когда они не используются. Для многих ситуаций, таких как тестирование или стэйджинг, вам не нужны инстансы работающие 24/7, и вам не нужно платить за EC2, когда они отключены. Учитывая, что затраты рассчитываются на основе использования, это простой механизм для экономии затрат. Это может быть достигнуто посредством использования [Lambda and CloudWatch](https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/), решения с открытым кодом [cloudcycler](https://github.com/fairfaxmedia/cloudcycler), или SaaS решение типа [GorillaStack](https://www.gorillastack.com). (Примечание: если вы выключаете инстанс с эфемерным корневым томом, данные будут утрачены. Поэтому, для приложений с сохранением состояния безопаснее выключать инстансы с EBS томом.)\n-\t[**Выделенные инстансы**](https://aws.amazon.com/ec2/purchasing-options/dedicated-instances/) и [**выделенные хосты**](https://aws.amazon.com/ec2/dedicated-hosts/) - это выделенное оборудование, вместо обычных виртуальных инстансов. Они значительно дороже, нежели виртуальные инстансы, но [могут предпочитаться](https://aws.amazon.com/ec2/dedicated-hosts/) по причинам производительности, соответствия, финансовой модели или лицензирования.\n-\t**32 bit и 64 bit:** Несколько micro, small и medium инстансов пока доступны для использования 32-битной архитектуры. В наше время вы будете использовать 64-битные инстансы EC2 (“amd64”), хотя мелкие инстансы пока поддерживают 32-бита (“i386”). Используйте 64-битную архитектуру, кроме случаев, когда у вас  есть наследственные ограничения или другая хорошая причина чтобы использовать 32-битную.\n-\t**HVM и PV:** Есть два вида технологии виртуализации используемой EC2, [железная виртуальная машина (HVM) и паравиртуализация (PV)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/virtualization_types.html). Исторически, PV был основным типом, но [сейчас HVM становится стандартом](https://www.opswat.com/blog/aws-2015-why-you-need-switch-pv-hvm). Если вы хотите использовать новейшие типы инстансов, вы должны использовать HVM. Смотрите [матрицу типов инстансов](https://aws.amazon.com/amazon-linux-ami/instance-type-matrix/) для подробностей.\n-\t**Операционные системы:** Чтобы использовать EC2, вам необходимо выбрать базовую операционную систему. Это может быть Windows или Linux, например Ubuntu или [Amazon Linux](https://aws.amazon.com/amazon-linux-ami/). Это делается посредством AMI, которые более раскрыты в отдельном разделе ниже.\n-\t**Лимиты:** Вы не можете создать произвольное количество инстансов. Лимиты количества инстансов EC2 по умолчанию на аккаунт варьируются по типам инстансов, как описано в [этом списке](http://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2).\n-\t❗**Используйте защиту от удаления:** Для любых инстансов, которые важны и долго работают (в частности, не являются частью автомасштабирования), [включайте защиту от удаления](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#Using_ChangingDisableAPITermination). Это важная линия защиты от ошибок пользователя, таких как случайное удаления многих инстансов вместо одного из-за человеческой ошибки.\n-\t**Управление ключами SSH:**\n\t-\tКогда вы запускаете инстанс, вам необходимо настроить хотя бы одну [пару ключей ssh](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) для первоначальной настройки, чтобы позволить вам подключиться по ssh в первый раз. \n\t-\tПомимо начальной настройки, вы должны сами управлять ключами в инстансах, назначая индивидуальные ключи отдельным пользователям или службам в зависимости от ситуации.\n\t-\tИзбегайте повторного использования оригинальных ключей, кроме как администраторами, при создании новых инстансов.\n\t-\tНе делитесь ни с кем ключами и [добавьте индивидуальные ssh ключи](http://security.stackexchange.com/questions/87480/managing-multiple-ssh-private-keys-for-a-team) конкретным пользователям.\n-\t**Поддержка GPU:** Вы можете арендовать инстансы с поддержкой графического процессора в EC2 для использования в целях машинного обучения или рендеринга графики.\n\n\t-\tСейчас доступно [три типа](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using_cluster_computing.html) инстансов с поддержкой графического процессора:\n\t\t- Тип P3 предлагает графические процессоры NVIDIA Tesla V100 в конфигурации 1, 4 или 8 GPU для использования в целях машинного обучения, научных и других высокопроизводительных вычислительных задач.\n\t\t- Тип P2 предлагает графические процессоры NVIDIA Tesla K80 в конфигурации 1, 8 или 16 GPU для использования в целях машинного обучения, научных и других высокопроизводительных вычислительных задач.\n\t\t- Тип G3 предлагает графические процессоры NVIDIA Tesla M60 в конфигурации 1, 2 или 4 GPU для использования в целях рендеринга графики и обработки видео.\n\t-\tAWS предлагает два различных AMI, которые используются с GPU ориентированными приложениями. В частности, они нацелены на рабочие задачи глубокого обучения, но также предоставляют доступ к более урезанным базовым образам только для поддержки драйверов.\n\t\t-\tAWS предлагает Amazon Linux [Deep Learning AMI](https://aws.amazon.com/marketplace/pp/B077GF11NF?qid=1536363169916&sr=0-3&ref_=srh_res_product_title) (на базе Amazon Linux) а также Ubuntu [Deep Learning AMI](https://aws.amazon.com/marketplace/pp/B077GCH38C). Оба образа идут с большинством драйверов NVIDIA и сопутствующим программным обеспечением (CUDA, CUBLAS, CuDNN, TensorFlow, PyTorch, и т.д.) дабы снизить барьер использования.\n\t\t-\t⛓ Имейте ввиду, что использование этих AMI может привести к привзяке, так как у вас нет прямого доступа к конфигурации или версиям программного обеспечения.\n\t\t-\t🔸 Компендиум включенных фреймворков может привести к длительному времени запуска инстансов и сложным для понимания средам.\n\t-\t🔹Как в случае с любыми дорогими типами инстансов EC2, [спот инстансы могут предложить значительную экономию](#управление-затратами-на-ec2) с GPU-ориентированными задачами, когда прерывания не критичны.\n- Все текущие типы инстансов EC2 могут использовать преимущества адресации IPv6, если они запускаются в подсети с выделенным диапазоном CIDR в VPC с поддержкой IPv6.\n\n### Ошибки и ограничения EC2\n\n-\t❗Никогда не используйте ssh пароли. Просто не делайте этого; они слишком небезопасны, а последствия компроментации слишком серьезны. Используйте вместо этого ключи. [Прочтите это](https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2) и полностью отключите парольный доступ на вашем ssh сервере, удостоверившись, что параметр 'PasswordAuthentication no' прописан в конфигурационном файле /etc/ssh/sshd_config. Если вы бережно заботитесь об управлении приватными ключами ssh, где бы они не хранились, это значительное улучшение безопасности по сравнению с аутентификацией на основе пароля.\n-\t🔸Для всех [новых типов инстансов](https://aws.amazon.com/amazon-linux-ami/instance-type-matrix/), когда выбираете AMI для использования, удостоверьтесь, что вы выбрали HVM AMI, или он просто не заработает.\n-\t❗При создании инстанса и использовании новой пары ключей ssh [убедитесь, что права доступа для ключа ssh указаны правильно](http://stackoverflow.com/questions/1454629/aws-ssh-access-permission-denied-publickey-issue).\n-\t🔸Иногда определенные инстансы EC2 могут быть запланированы для вывода из эксплуатации AWS из-за  “обнаруженной деградации подлежащего оборудования”, в этом случае вам будет предоставлено пару недель для миграции на новый инстанс.\n \t-\tЕсли корневой том на вашем инстансе является томом EBS, вы можете просто выключить и включить инстанс, таким образом он переместится на рабочее оборудование, таким образом вы можете сами контролировать время данного процесса. Имейте ввиду, что вы потеряете данные на ([эфемерных дисках](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html)) если тип вашего инстанса подразумевает хранение данных на дисках инстанса.\n \t-\tПубличный IP адрес инстанса(если таковой имеется) скорее всего изменится если вы не используете Elastic IPs. Это может быть проблемой, если другие системы зависят от IP адресов.\n-\t🔸Периодически вы можете обнаружить, что ваш сервер или балансировщик нагрузки получает трафик (предположительно) предыдущего сервера EC2, который работал с тем же IP-адресом, который вы получили сейчас (это может не иметь значения, или это можно исправить путем перехода на другой инстанс).\n-\t❗Если API EC2 является критичным компонентом вашей инфраструктуры(например для автоматической замены серверов, пользовательских алгоритмов масштабирования и т.д.) и вы работает в крупных масштабах или делаете множество вызовов API EC2, удостоверьтесь, что вы понимаете, что это может вас подвести (вызовы к API [ограничены по частоте](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/query-api-troubleshooting.html#api-request-rate) и ограничения не опубликованы и не подлежат изменениям) таким образом, учитывайте эту возможность при разработке и тестировании.\n-\t❗Многие новые типы инстансов EC2 либо используют только EBS, либо поддерживаются локальными дисками NVMe, назначенными этому инстансу. При планировании их использования обязательно учитывайте производительность и затраты EBS.\n-\t❗Если вы работаете в значительном масштабе, вы можете разделить вызовы API, которые перечисляют все ваши ресурсы, и вместо этого оперировать либо отдельными ресурсами, либо подмножеством всего списка. API EC2 может вернуть таймаут! Попробуйте использовать [фильтры](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) чтобы ограничивать то, что возвращается.\n-\t❗⏱ Инстансы также бывают двух видов: **Инстансы с постоянной производительностью** (например, M3, C3 и R3) и [**Инстансы с разгоняющейся производительностью**](https://aws.amazon.com/ec2/instance-types/#burst) (например, T2). Инстанс T2 получает кредиты CPU постоянно, частота зависит от размера инстанса. Инстансы T2 накапливают кредиты CPU когда простаивают, и используют кредиты CPU, когда активны. Как бы там не было, как только кредиты закончатся, вы заметите серьезную просадку в производительности. Если вам нужна постоянная высокая производительность CPU для приложений типа обработки видео, вебсайтов с высокой нагрузкой или  высокопроизводительных вычислений, рекомендуется использовать инстансы с постоянной производительностью.\n-\tПользовательские данные инстанса [ограничены 16 KB](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-add-user-data). (Это ограничение применяется к данным в сыром виде, не закодированным в base64.) Если необходимо больше данных, они могут быть скачаны с S3 посредством использования скрипта в пользовательских данных.\n-\tСовсем новые аккаунты могут не иметь возможности запускать некоторые типы инстансов, например инстансы с GPU, из-за изначально установленного “мягкого ограничения”, равного нулю. Этот лимит может снят путем запроса в поддержку. Ознакомьтесь [с сервисными ограничениями AWS](http://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html) для понимания методов подачи запроса в поддержку. Имейте ввиду, что данный лимит на текущий момент [не документирован](http://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_ec2).\n- Поскольку множество инстансов совместно запускается на одном и том же физическом оборудовании, первые пользователи облачных технологий  столкнулись с так называемой [проблемой шумных соседей](https://searchcloudcomputing.techtarget.com/definition/noisy-neighbor-cloud-computing-performance). Ощущение того, что ты не получаешь того, за что платишь приводит к [фрустрации у пользователей](https://twitter.com/technicallyjosh/status/668963405831651328), как бы там не было, \"кража\" не самое лучшее слово, которое описывает, что происходит на самом деле, на основе [детального объяснения того, как ядро определяет украденное время](https://support.cloud.engineyard.com/hc/en-us/community/posts/203751578-Explanation-of-Steal-Time). Для того, чтобы избежать воздействия эффекта украденного времени на ваше приложение, лучшим вариантом является [правильный дизайн вашей облачной архитектуры](https://www.infoworld.com/article/3073503/cloud-computing/debunking-the-clouds-noisy-neighbor-myth.html).\n- AWS [представила выделенную аренду](https://aws.amazon.com/blogs/aws/amazon-ec2-dedicated-instances/) в 2011 году. Это позволяет клиентам размещать все ресурсы на едином сервере. Некоторые видят в этом решение [проблемы шумных соседей](https://www.infoworld.com/article/3008225/cloud-computing/amazon-dedicated-hosts-bye-bye-to-noisy-cloud-neighbors.html) так как только один клиент использует процессорную мощность. Однако этот подход идет с серьезным риском, в случае если оборудованию потребуется любой тип обслуживания. Если у клиента есть 20 запущенных инстансов в распределенной аренде и один подлежащий сервер требует обслуживания, инстансы только на этом сервере будут отключены.А вот если у клиента 20 инстансов запущено в выделенной аренде, тогда при обслуживании подлежащего оборудования - все 20 инстансов будут отключены.\n-\t🔸Только тип инстанса **i3.metal** предоставляет возможность запускать эмуляторы Android x86 в AWS на текущий момент.\n\n\n\nCloudWatch\n-------------------\n\n### Основы CloudWatch \n\n* 📒  [Домашняя страница](https://aws.amazon.com/cloudwatch/) ∙ [Документация](https://aws.amazon.com/documentation/cloudwatch/) ∙ [ЧаВо](https://aws.amazon.com/cloudwatch/faqs/) ∙ [Расценки](https://aws.amazon.com/cloudwatch/pricing/)\n* **CloudWatch** мониторит ресурсы и приложения, собирает логи, и шлет уведомления.\n* Мониторинг CloudWatch - это стандартный механизм отслеживания ресурсов AWS. Широкий диапазон  [**метрик и измерений**](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CW_Support_For_AWS.html) доступен в CloudWatch, позволяя вам создавать временные графики, **[тревоги](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)**, и **[панели мониторинга](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)**.\n    * Аварийная тревога - наиболее практичное использование CloudWatch, позволяющее запускать уведомления от любого заданного показателя.\n    * Тревоги могут включать [оповещения SNS](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ConsoleAlarms.html), [действия автоматического масштабирования](http://docs.aws.amazon.com/autoscaling/latest/userguide/policy_creating.html), или [действия связанные с EC2](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html).\n    * Тревоги также поддерживают возможность [оповещения, когда количество M из N источников данных пересекает порог оповещения](https://aws.amazon.com/about-aws/whats-new/2017/12/amazon-cloudwatch-alarms-now-alerts-you-when-any-m-out-of-n-metric-datapoints-in-an-interval-are-above-your-threshold/).\n    * Публикуйте и делитесь графиками метрик путем создания [настраиваемых панелей мониторинга](https://aws.amazon.com/blogs/aws/cloudwatch-dashboards-create-use-customized-metrics-views/).\n\t\t* Мониторинг и создание отчетов по [оповещениям ошибок проверки состояния системы инстанса](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html#creating_status_check_alarms).\n* **Использование CloudWatch Events:**\n    * События(Events) создают механизм для автоматизации действий в различных сервисах на AWS. Вы можете создать [правила событий](http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html) для состояний инстанса, AWS API, Автоматического масштабирования(Auto Scaling), AWS Systems Manager Run Command, развертываний или расписаний (вспомните Cron).\n    * [Запущенные события(Triggered events)](http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CWE_GettingStarted.html) могут вызывать функции Lambda, посылать сообщения SNS/SQS/Kinesis, или делать что-то с инстансом (удалять, перезапускать, останавливать, или делать снапшоты томов).\n    * Пользовательские данные могут быть посланы целям в формате JSON, особенно это полезно, когда запускаешь Lambda.\n* **Использование CloudWatch Logs:**\n    * [CloudWatch Logs](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) - это система для потокового хранения логов. Путем хранения логов в AWS вы получаете неограниченное платное хранилище, кроме того, вы имеете возможность направлять потоки логов напрямую в ElasticSearch или в свои Lambda.\n    * [Log-агент, установленный](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_GettingStarted.html) на ваши сервера будет собирать логи все время и посылать их в CloudWatch Logs.\n    * Вы можете [экспортировать данные логов в S3](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/S3Export.html) или направить потоки в другие сервисы AWS.\n    * CloudWatch Logs может быть [зашифрована используя ключи, управляемые KMS](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html).\n* **Детальный мониторинг:** [Детальный мониторинг](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch-new.html) должен быть включен для инстансов EC2 для получения гранулярных метрик и [оплачивается с CloudWatch](https://aws.amazon.com/cloudwatch/pricing/).\n\n### Альтернативы CloudWatch и привязки\n\n* CloudWatch предлагает довольно базовую функциональность, которая не создает значительную (дополнительную) привязку к AWS. Большинство метрик, предоставляемых сервисом, могут быть получены через API, которые могут быть импортированы в другие средства сбора или визуализации  (многие предоставляют специальный сервис по импорту данных с CloudWatch).\n* 🚪 Альтернативы мониторингового сервиса CloudWatch включают в себя - [NewRelic](http://newrelic.com/), [Datadog](http://datadog.com/), [Sumo Logic](http://sumologic.com/), [Zabbix](http://zabbix.com/), [Nagios](http://nagios.org/), [Ruxit](http://ruxit.com/), [Elastic Stack](https://www.elastic.co/elk-stack), варианты с открытым кодом, такие как [StatsD](https://github.com/etsy/statsd) or [collectd](https://collectd.org/) с [Graphite](https://graphiteapp.org/) и многие другие.\n* 🚪 Альтернативы по хранению логов CloudWatch включают в себя - [Splunk](http://splunk.com/), [Sumo Logic](http://sumologic.com/), [Loggly](http://loggly.com/), [LogDNA](https://logdna.com/), [Logstash](https://www.elastic.co/products/logstash), [Papertrail](https://papertrailapp.com/), [Elastic Stack](https://www.elastic.co/elk-stack) и другие решения по централизованному хранению логов.\n\n### Советы по CloudWatch\n\n* Некоторые из наиболее распространненых случаев применения CloudWatch - **[оповещения о превышении затрат](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html)**, **оповещение, что инстанс** **или [балансировщик нагрузки упал/поднялся](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-cloudwatch-metrics.html)**, и **оповещения об использовании дискового пространства**.\n* Вы можете использовать [EC2Config](http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_WinAMI.html#send_logs_to_cwl) для мониторинга метрик памяти и дискового пространства на инстансах под управлением Windows. Для Linux существуют [примеры скриптов](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/mon-scripts.html), которые делают то же самое.\n* Вы можете [опубликовать свои собственные метрики](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html) используя API AWS. [Включает дополнительные затраты](https://aws.amazon.com/cloudwatch/pricing/).\n* Вы можете направить потоковые логи с CloudWatch Logs в Lambda или кластер ElasticSearch путем создания [подписок](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Subscriptions.html) на группы логов(Log Groups).\n* Не забудьте воспользоваться Не забудьте воспользоваться преимуществом [всегда бесплатных услуг CloudWatch](https://aws.amazon.com/free/#Amazon_CloudWatch).\n\n### Ошибки и ограничения, связанные с CloudWatch\n\n* 🔸Метрики в CloudWatch снимаются на уровне [гипервизора](https://forums.aws.amazon.com/message.jspa?messageID=403578). Гипервизор не имеет доступа к информации на уровне операционной системы, таким образом отдельные метрики (в основном утилизация памяти) не доступна пока не передана в CloudWatch с агента, установленного внутри инстанса.\n* 🔸Вы не можете использовать [более одной метрики на оповещение](https://forums.aws.amazon.com/thread.jspa?threadID=94984).\n* 🔸Оповещения получаемые в случае тревоги не содержат контекстной информации; они содержат информацию о пределе, состоянии тревоги и времени.\n* 🔸По умолчанию, разрешение метрик в CloudWatch равно 1 минуте. Если вам необходимо посылать несколько знанчений метрики в пределах одной и той же минуты, они будут собраны в минимум, максимум, среднее и общее(суммарное) значение в минуту.\n* 🐥В июле 2017 года, была добавлена новая [опция высокого-разрешения](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html#high-resolution-metrics) для метрик и аварийных оповещений CloudWatch. Эта функция позволяет вам записывать данные метрик с разрешением в одну секунду и оценивать состояние тревоги CloudWatch каждые 10 секунд.\n    - Это [информационное сообщение, представляющее данную возможность](https://aws.amazon.com/blogs/aws/new-high-resolution-custom-metrics-and-alarms-for-amazon-cloudwatch/) описывает, как опубликовать метрику высокого разрешения в CloudWatch. Имейте ввиду, когда вы вызываете `PutMetricData` API, `StorageResolution` является атрибутом каждого элемента, который вы посылаете в массив `MetricData`, а не прямой параметр вызова `PutMetricData`.\n* 🔸Данные метрик хранятся в CloudWatch [15 месяцев](https://aws.amazon.com/blogs/aws/amazon-cloudwatch-update-extended-metrics-retention-user-interface-update/), начиная с ноября 2016 года (раньше было 14 дней). Минимальная гранулярность вырастает через 15 дней.\n\nAMIs\n----\n\n### Основы AMI\n\n-\t📒 [Руководство пользователя](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)\n-\t**AMIs** Образы машин Amazon(Amazon Machine Images) - неизменяемые образы, которые используются для запуска предварительно сконфигурированных EC2 инстансов. Они бывают двух видов - общедоступные и частные. Общедоступные AMI либо доступны бесплатно (общие или созданные сообществом AMI) или покупаются и продаются на [**AWS Marketplace**](http://aws.amazon.com/marketplace).\n-\tМногие производители операционных систем публикуют готовые к использованию базовые AMI. Например для Ubuntu, смотри [Поиск Ubuntu AMI](https://cloud-images.ubuntu.com/locator/ec2/). У Amazon конечно же есть список [AMI Amazon Linux](https://aws.amazon.com/amazon-linux-ami/).\n\n### Советы по AMI\n\n-\tAMIs создаются независимо, на основе того, как они будут развернуты. Вы должны подобрать AMI, которые соответствуют вашему развертыванию, когда используете или создаете их:\n\t-\tEBS или хранилище на инстансе\n\t-\tPV или HVM [типы виртуализации](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/virtualization_types.html)\n\t-\t32 битная (“i386”) или 64 битная (“amd64”) архитектура\n-\tКак описано выше, современные развертывания будут обычно использовать **64-битную HVM с EBS**.\n-\tВы можете создать свой собственный AMI путем создания [мгновенного снимка состояния(снапшота)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html) EC2 инстанса, который вы сконфигурировали.\n-\t[AMI с EBS хранилищем](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device) содержит необходимые образу данные на томе EBS, и не требует дополнительных операций по извлечению данных с S3, что приводит к тому, что инстансы с EBS загружаются быстрее, нежели инстансы с внутренним хранилищем.\n-\t**AMI различаются в разных регионах**, таким образом вы должны найти необходимый AMI в вашем регионе, или скопировать ваши AMI между регионами при помощи функции [AMI Copy](https://aws.amazon.com/about-aws/whats-new/2013/03/12/announcing-ami-copy-for-amazon-ec2/).\n-\tКак и при работе с другими ресурсами AWS, будет мудрым выбором [использовать метки(тэги)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) для обеспечения версионности AMI и управления их жизненным циклом.\n-\tЕсли вы создаете свои собственные AMI, всегда есть некоторые сложности в выбори того, сколько и чего вы хотите установить, сконфигурировать и “впечь” в эти образы.\n\t-\tЕсли вы вкладываете меньший объем в ваш AMI (например, только клиент управления конфигурацией, который загружает, устанавливает и настраивает программное обеспечение на новых инстансах EC2 при их запуске) позволяет вам сократить временные затраты на автоматизацию создания AMI и управления жизненным циклом AMI (у вас скорее всего будет возможность использовать меньшее количество AMI и вам не придется часто их обновлять), но это приводит к более долгому ожиданию прежде чем инстансы будут готовы к использовани, что, в свою очередь, приводит к более высокой вероятности сбоев установки или конфигурации во время запуска.\n\t-\tЕсли вы вкладываете больший объем в ваш AMIs (например, предустанавливаете, но не полностью настраиваете базовое программное обеспечение, вместе с клиентом управления конфигурацией, который подгружает конфигурационные настройки во время загрузки) приводит к более быстрому запуску и меньшему количеству возможностей появления ошибок во время установки программного обеспечения и его конфигурирования во время запуска инстанса, однако в то же время повышает необходимость создания и управления быстрого конвеера по созданию AMI.\n\t-\tЕсли вы вкладываете еще больший объем в ваш AMIs (например, устанавливаете все необходимое программное обеспечение, а также настраиваете конфигурацию для конкретного окружения) приводит к быстрому запуску и гораздо меньшей вероятности сбоев во время запуска инстанса, но (без принятия во внимание дополнительные переразвертываний и перенастройки) может потребовать трудозатратных обновлений AMI в целях обновления программного обеспечения или конфигурирования, также как и более сложный процесс автоматизации создания AMI.\n-\tКакой вариант вы предпочтете, зависит от того, как быстро вам необходимо масштабировать Which option you favor depends on how quickly you need to scale up емкость, а также от размера и зрелости вашей команды и продукта.\n\t-\tКогда инстансы загружаются быстро, автоматически масштабируемые сервисы требуют меньшего количества встроенных запасных мощностей и могут быстрее масштабироваться в ответ на внезапное повышение нагрузки. Когда вы создаете сервис с автоматическим масшабированием, позаботьтесь о вложении как можно большего количества предустановок и настроек в ваш AMI и готовьте их с поддержкой хранилища EBS.\n\t-\tAПо мере того, как системы становятся больше, обычно требуется более сложное управление AMI, такое как многоэтапный процесс создания AMI, в котором несколько (в идеале один) общих базовых AMI редко пересобираются, для обновления компонентов, общих для всех развернутых служб, а затем, более часто, запускается сборка AMI “для уровня сервиса” AMI которая включает в себя установку программного обеспечения и настройку для определенного сервиса.\n-\tБольше размышлений относительно стратегий создания AMI [тут](http://techblog.netflix.com/2013/03/ami-creation-with-aminator.html).\n-\tИспользуйте инструменты вроде [Packer](https://packer.io/) для упрощения и автоматизации создания AMI.\n-\tЕсли вы используете инстансы на RHEL и так случилось, что у вас действующая подписка Red Hat на использование RHEL в локальном дата-центре, тогда вы можете использовать программу Red Hat [Cloud Access](https://www.redhat.com/en/technologies/cloud-computing/cloud-access) чтобы перенести часть ваших подписок в AWS, таким образом AWS не будет выставлять вам повторные счета за использование RHEL подписок. Вы можете использовать либо самостоятельно созданные RHEL AMI или предоставленные Red Hat [Золотые образы(Gold Images)](https://access.redhat.com/articles/2962171) которые будут добавлены в ваш частный каталог AMI, как только вы подпишетесь на программу Red Hat Cloud Access.\n\n### Ошибки и ограничения, связанные с AMI\n\n-\t🔸**Версии пакета Amazon Linux:** [По умолчанию](https://aws.amazon.com/amazon-linux-ami/faqs/#lock), инстансы на основе Amazon Linux AMI настроены на использование последних версий пакетов в репозитории Amazon. Это значит, что версии устанавливаемых пакетов не заблокированы и могут измениться, в том числе может произойти ситуация, когда программное обеспечение будет сломано при обновлении в будущем. Если вы готовите AMI с уже примененными обновлениями, это вряд-ли вызовет проблемы в запущенных сервисах, чьи инстансы базируются на этих AMI – проблема возникнет на ранней стадии создания процесса сборки AMI, и должна быть исправлена или устранена до момента генерации AMI. Существует функция “блокировка при запуске(lock on launch)”, которая позволяет жестко закрепить использвование инстансами на Amazon Linux репозитория с конкретными мажорными версиями Amazon Linux AMI, снижая вероятность того, что проблемы и поломки, вызванные изменением версий по инициативе Amazon затронут время установки пакета, однако цена - отсутствие обновления пакетов.Сочетание использования функции «блокировка при запуске» с процессом усовершенствования Amazon Linux AMI по вашему усмотрению может обеспечить более жесткий контроль над поведением и временем обновления.\n-   **Настройки Cloud-Init по умолчанию:** Часто пользователи создают AMI после проведения кастомизации (неважно вручную или с использованием инструментов, таких как Packer или Ansible).  Если вы не придали значения настройкам cloud-init, которые относятся к системным службам(например sshd, и т.д.) которые вы настроили, вы можете заметить, что изменения, которые вы внесли не актуальны после первого запуска вашего нового AMI, так как cloud-init их перезаписал.\n\n    В некоторых дистрибутивах используются другие файлы, нежели в других дистрибутивах, но все они обычно расположены в  `/etc/cloud/`, независимо от дистрибутива. Вам следует пересмотреть эти файлы крайне внимательно, с учетом выбранного дистрибутива, перед созданием вашего собственного AMI.  [Полный справочник по cloud-init](https://cloudinit.readthedocs.io/en/latest/) доступен на сайте cloud-init.  Это расширенный механизм настройки, поэтому перед любым серьезным использованием протестируйте любые изменения, внесенные в эти файлы, в изолированной среде(песочнице).\n\nAuto Scaling (Автоматическое масштабирование)\n------------\n\n### Основы Auto Scaling\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/autoscaling/) ∙ [Руководство пользователя](http://docs.aws.amazon.com/autoscaling/latest/userguide/) ∙ [ЧаВо](https://aws.amazon.com/ec2/faqs/#Auto_Scaling) ∙ [Расценки](https://aws.amazon.com/autoscaling/pricing/) at no additional charge\n-\t[**Группы Автоматического Масштабирования(Auto Scaling Groups (ASGs))**](https://aws.amazon.com/autoscaling/) используются для контроля количества инстансов в сервисе, сокращая ручную работу на создание или удаление инстансов EC2.\n-\tОни могут быть сконфигурированы посредством [Политик Масштабирования(Scaling Policies)](http://docs.aws.amazon.com/autoscaling/latest/userguide/policy_creating.html) для автоматического увеличения или уменьшения количества инстансов на основании метрик, такиих как утилизация CPU или на основе расписания.\n-\tЕсть три основных способа использования ASG - динамический (автоматическая настройка количества инстансов на основе метрик таких, как загрузка процессора), статическая (поддержка определенного количества инстансов все время), по расписанию (поддержка различного количества инстансов в разное время суток или дней недели).\n-\t💸ASG [не оплачивается дополнительно](https://aws.amazon.com/autoscaling/pricing/); вы платите только за низлежащие EC2 инстансы и сервисы CloudWatch.\n\n### Советы по автоматическому масштабированию\n\n-\t💸 Лучшее соответствие размера кластера вашим текущим требованиям к ресурсам за счет использования ASG может привести к значительной экономии средств для многих типов рабочих нагрузок.\n-\tСовместное использование ASG с CLB - общая схема, используемая для того, чтобы справляться с изменениями объема трафика, который получает сервис.\n-\tДинамическое автоматическое масштабирование проще всего использовать с горизонтально масштабируемыми сервисами без требования сохранения состояния.\n-\tДаже если вы не используете ASG для динамического увеличения или уменьшения количества экземпляров, вам следует серьезно рассмотреть возможность хранения всех инстансов внутри ASG - учитывая количество целевых инстансов, ASG будет работать, чтобы гарантировать, что число запущенных инстансов будет равно этому целевому значению, заменяя инстансы, если они умирают или помечены как нездоровые. Это приводит к постоянной емкости и лучшей стабильности вашего сервиса.\n-\tСервис масштабирования может быть [сконфигурирован уничтожать](http://docs.aws.amazon.com/autoscaling/latest/userguide/healthcheck.html) инстансы, которые помечены балансировщиками нагрузки, как нездоровые.\n\n### Ошибки и ограничения, связанные с автоматическим масштабированием\n\n-\t🔸**Параметр ReplaceUnhealthy :** По умолчанию, ASGs убьет инстансы, которые не отвечают. Это возможно для тех инстансов, процессор которых загружен полностью на несколько минут и которые не отвечают на запросы, таким образом, ASG с настроенным по умолчанию [параметром ReplaceUnhealthy](http://docs.aws.amazon.com/autoscaling/latest/userguide/as-suspend-resume-processes.html#process-types) заменит их. Есть смысл отключить эту настройку, в случаях если инстансы управляемые ASG часто работают с высокой нагрузкой на процессор. В таком случае, определение и уничтожение нездоровых инстансов перейдет под вашу ответственность.\n\nEBS\n---\n\n### Основы EBS\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/ebs/) ∙ [Руководство пользователя](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) ∙ [ЧаВо](https://aws.amazon.com/ebs/faqs/) ∙ [Расценки](https://aws.amazon.com/ebs/pricing/)\n-\t**EBS** (Elastic Block Store) предоставляет блочное хранилище данных. Да, он предлагает тома хранилища данных, которые могут быть подключены, как файловые системы, как традиционные сетевые диски.\n-\tТома EBS могут быть подключены только к одному инстансу EC2 на момент времени. В отличии от EFS, который может быть подключен между многими серверами, но стоит дороже ([сравнение](http://stackoverflow.com/questions/29575877/aws-efs-vs-ebs-vs-s3-differences-when-to-use)).\n\n### Советы по EBS\n\n-\t⏱**RAID:** Используйте [RAID диски](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/raid-config.html) для [повышенной производительности](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSPerformance.html).\n-\t⏱Стоило бы прочитать [публикацию AWS о характеристиках ввода-вывода EBS](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-io-characteristics.html) также как и их [советы по производительности](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSPerformance.html#d0e86148).\n-\t⏱Можно [выделить IOPS](http://aws.amazon.com/ebs/details/) (что означает - платить за определенный уровень операций ввода-вывода в секунду), чтобы обеспечить определенный уровень производительности диска.\n-\t⏱Один том gp2 EBS позволяет в максимуме достигнуть 16k IOPS. Для того, чтобы выжать максимум производительности из тома gp2 EBS, он должен быть максимального размера и быть подключенным к EBS-optimized инстансу EC2.\n- \t💸Стандартные и gp2 тома EBS повышают характеристику IOPS с размером. Возможно, имеет смысл просто увеличить объем, вместо того, чтобы явно платить за лучшую производительность. Это может во многих случаях сократить расходы на 2/3.\n-\tСтандартный размер блока для тома EBS - 16kb.\n\n### Ошибки и ограничения, связанные с EBS\n\n-\t❗EBS достаточно надежен для обычного жесткого диска (средняя годовая частота отказов [между 0.1% - 0.2%](http://aws.amazon.com/ebs/details/#availabilityanddurability)). С другой стороны, это очень плохо, если у вас нет резервных копий. В отличии от EBS, надежность S3 экстремально высокая. *Если вы заботитесь о своих данных, делайте их резервную копию на S3 с использованием снапшотов.*\n-\t🔸EBS предоставляет [**SLA**](http://aws.amazon.com/ec2/sla/) с показателем работоспособности в **99.99%**. Смотрите примечания о высокой доступности ниже.\n-\t❗Тома EBS имеют [**тип тома**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) указывающий на физический тип хранилища. “Стандартный” тип (**st1** or **sc1**) в реальности обычный диск на вращающихся пластинах, которые могут обеспечить только сотни IOPS — совсем не то, что вам обычно нужно, кроме случаев, когда вы хотите сильно урезать издержки. Современные типы основанные на SSD **gp2** или **io1** обычно тот вариант, который вам нужен.\n-\t❗Когда восстанавливаешь снапшот для создания EBS тома, блоки считываются медленно с S3 поначалу. Во избежание первоначального периода высоких задержек, вы можете использовать `dd` или `fio` согласно [официальной документации](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-restoring-volume.html).\n\nEFS\n---\n\n\n### Основы EFS \n\n-\t📒 [Домашняя страница](https://aws.amazon.com/efs/) ∙ [Руководство пользователя](http://docs.aws.amazon.com/efs/latest/ug) ∙ [ЧаВо](https://aws.amazon.com/efs/faq/) ∙ [Расценки](https://aws.amazon.com/efs/pricing/)\n-\t🐥**EFS** это сетевая файловая система Amazon. Она представляет из себя сервер [NFSv4.1](https://en.wikipedia.org/wiki/Network_File_System#NFSv4). Любой клиент совместимый NFSv4 может подключить ее.\n-\tОна разработана для обеспечения высокой доступности и надежности, и каждый объект файловой системы EFS избыточно хранится в нескольких зонах доступности.\n-\tEFS предназначена для использования в качестве общего сетевого диска и может автоматически масштабироваться до петабайт хранимых данных и тысяч инстансов, подключенных к нему.\n-\tEFS может предложить [более высокую пропускную способность](http://docs.aws.amazon.com/efs/latest/ug/performance.html) (множество гигабайт в секунду) более высокую надежность и доступность нежели EBS (смотрите [сравнительную таблицу](#долговечность-и-надежность-хранения-доступность-и-цена)), но при этом задержки будут выше.\n-\tЦена EFS основана на объеме хранимых данных и стоит [намного дороже, чем EBS](#долговечность-и-надежность-хранения-доступность-и-цена); Это примерно в три раза больше по сравнению с томами общего назначения gp2 в EBS.\n-\t⏱ [Производительность](http://docs.aws.amazon.com/efs/latest/ug/performance.html) зависит от объема хранимых данных, как и цена:\n\t-\tКак и EBS, EFS использует кредитную систему. Кредиты зарабатываются с частотой 50 KiB/s на GiB хранилища и потребляются для увеличения скорости во время чтения/записи файлов и метаданных. В отличии от EBS, операции на метаданных (размер файла, владелец, дата создания и т.д.) также потребляют кредиты. [Метрика BurstCreditBalance](http://docs.aws.amazon.com/efs/latest/ug/monitoring-cloudwatch.html#efs-metrics) в CloudWatch должна мониториться, чтобы убедиться, что файловая система не осталась без кредитов.\n\t-\tМаксимальный объем пропускной способности во время ускорения также зависит от размеров хранимых данных. До 1 TiB - пропускная способность может доходить до 100 MiB/s. Выше этого знанчения, 100 MiB/s добавляется за каждый хранимый TiB. Например, файловая система хранящая 5 TiB может разгоняться до скорости в 500 MiB/s. Максимальная пропускная способность на инстанс EC2 - 250 MiB/s.\n\t-\tEFS имеет два режима производительности, которые могут быть выбраны когда создается файловая система. Первый \"General Purpose\", второй \"Max I/O\". Max I/O масштабируется больше, но ценой более высоких задержек. Если сомневаетесь, используйте General Purpose, который также является выбором по умолчанию. Если [метрика PercentIOLimit](http://docs.aws.amazon.com/efs/latest/ug/monitoring-cloudwatch.html#efs-metrics) в CloudWatch колеблется около 100%, рекомендуется Max I/O. Изменение режима производительности означает создание новой EFS и перенос данных. \n-\tВысокая доступность достигается наличием [точек подключения в различных подсетях/зонах доступности](http://docs.aws.amazon.com/efs/latest/ug/images/overview-flow.png).\n\n### Советы по EFS\n\n-\tПоскольку EFS основана на NFSv4.1, любой каталог в EFS можно подключить напрямую, он не обязательно должен быть корневым каталогом. Одно приложение может подключить *fs-12345678:/prog1*, другое - *fs-12345678:/prog2*.\n-\t[Разрешения на уровне групп и пользователей](https://docs.aws.amazon.com/efs/latest/ug/accessing-fs-nfs-permissions.html) можно использовать для контроля доступа к конкретным директориям на файловой системе EFS.\n-\t⏱ **Совместное использование файловых систем EFS:** Одна файловая система EFS может использоваться для нескольких приложений или служб, но это следует тщательно продумать:\n\n\tПлюсы:\n\t- Поскольку производительность основана на общем размере хранимых файлов, размещение всего на одном диске повысит производительность для всех. Одно приложение, потребляющее кредиты быстрее, чем оно может накопить, может быть компенсировано другим приложением, которое просто хранит файлы в EFS и редко обращается к ним.\n\n\tМинусы:\n\t- Поскольку кредиты используются совместно, если одно приложение использует их чрезмерно, это повлияет на другие.\n\t- Компромисс сделан в отношении [безопасности](http://docs.aws.amazon.com/efs/latest/ug/security-considerations.html): все клиенты будут иметь сетевой доступ к диску. Кто-то с правами доступа root на одном инстансе клиента может подключить любой каталог в EFS, и у него будет доступ на чтение и запись ко всем файлам на диске, даже если у них нет доступа к приложениям, размещенным на других клиентах. Для EFS нет эквивалента no-root-squash.\n\n### Ошибки и ограничения, связанные с EFS\n\n-\t🔸 Ряд функций NFSv4.1 [не поддерживается](http://docs.aws.amazon.com/efs/latest/ug/nfs4-unsupported-features.html) также существуют некоторые [лимиты](http://docs.aws.amazon.com/efs/latest/ug/limits.html) сервиса.\n-\t🔸 По состоянию на 08/2017, EFS предлагает возможность шифрования на уровне диска для новых дисков. Для файловых систем созданнных до этой даты, возможность шифрования может быть достигнута только переносом данных на новый том EFS.\n-\t🔸 Файловая система EFS [может быть подключена локально](https://aws.amazon.com/efs/faq/#on-premises) через Direct Connect.\n-\t🔸 Файловая система EFS не может быть подключена через сопряжение VPC или VPN, даже если VPN действует поверх Direct Connect.\n-\t🔸 Использование тома EFS в Windows не поддерживается.\n-\t⏱ Когда файл загружается в EFS, EFS может потребоваться несколько часов, чтобы обновить данные для выставления счетов и начисления кредитов.\n-\t🔸⏱  Операции с метаданными могут быть дорогостоящими с точки зрения массового потребления кредитов. При рекурсивном обходе дерева, содержащего тысячи файлов, можно легко увеличить потребление десятков или даже сотен мегабайт кредитов, даже если к файлам не притронулись. Команды типа ```find``` или ```chown -R``` могут оказать негативное влияние на производительность.\n\n\nБалансировщики нагрузки(Load Balancers)\n--------------\n\n### Основы Load Balancer\n\n-\tAWS предлагает три продукта в области балансировки нагрузки - “Классические балансировщики нагрузки(Classic Load Balancers)” (CLBs), “Программные балансировщики нагрузки(Application Load Balancers)” (ALBs), и \"Сетевые балансировщики нагрузки (Network Load Balancers)\" (NLB).\n-\tДо появления ALB, “Классические балансировщики нагрузки” были известны, как “Эластичные балансировщики нагрузки(Elastic Load Balancers)” (ELBs), поэтому в более ранней документации, инструментах и публикациях в блогах все еще могут содержаться ссылки на “ELB”.\n-\tCLB существуют с 2009 года, ALBs с 2016 года, NLBs были добавлены в AWS в 2017 году.\n-\tCLB поддерживает балансировку нагрузки по TCP и HTTP. ALB поддерживает балансировку нагрузки только по HTTP. NLB поддерживает балансировку нагрузки по TCP на 4 уровне модели OSI.\n-\tCLB и ALB может дополнительно терминировать SSL для одного сертификата SSL.\n-\tВсе они могут при необходимости выполнять активные проверки работоспособности инстансов и удалять их из пула назначения, если они стали не прошли проверку.\n-\tCLB не поддерживает сложную, основанную на правилах, маршрутизацию. ALB поддерживает набор (на текущий момент не особо большой) вариантов маршрутизации, основанных на правилах. NLB предлагает самые широкие возможности маршрутизации.\n-\tCLB может перенаправлять трафик только на один глобально настроенный порт в целевых инстансах, в то время как ALB может перенаправлять на порты, которые настроены для каждого инстанса, что лучше поддерживает маршрутизацию к службам в общих кластерах с динамическим назначением портов (например, ECS или Mesos). NLB поддерживает несколько портов на одном и том же IP-адресе; регистрацию целевых направлений по IP-адресам, включая целевые направления вне VPC, в котором находится балансировщик нагрузки; ECS может выбрать неиспользуемый порт для планирования таска, а затем зарегистрировать целевую группу, используя этот порт.\n-\tCLB поддерживаются, как в EC2 Classic, так и в VPC, в то время как ALB поддерживаются только в VPC.\n-   ALB могут использовать в целевых группах группы инстансов и цели на основе IP в диапазонах RFC1918, что позволяет использовать их для направления траффика на локальные сервера через VPN или Direct Connect.\n\n### Советы по Load Balancer\n\n-\tЕсли у вас заранее нет какого-либо мнения относительно балансировки нагрузки и нет сложных требований по балансировке нагрузки на основе специфичной для конкретного приложения маршрутизации запросов, разумным будет использовать CLB или ALB.\n-\tЕсли вы не хотите вообще думать о балансировке нагрузки, так как ваша архитектура крайне проста (скажем, только один сервер), все равно стоит поставить балансировщик нагрузки перед ним. Это даст вам большую гибкость во время обновления, так как вам не придется менять никакие настройки DNS, которые довольно таки долго распространяются, а также позволит вам делать некоторые вещи, типа терминации SSL гораздо легче.\n-\t**CLB и ALB могут иметь множество IP адресов:** Внутренне балансировщик нагрузки AWS - это просто набор отдельных программных балансировщиков нагрузки, размещенных в EC2, с распределением траффика путем балансировки нагрузки по DNS. Этот пул может содержать множество IP-адресов, как минимум по одному на каждую зону доступности и в зависимости от уровня нагрузки. Также они поддерживают терминацию SSL, что является очень удобным.\n-\t**Масштабирование:** CLB и ALB могут масштабироваться до очень высокой пропускной способности, однако масштабирование не является мгновенным процессом. Если вы ожидаете внезапного появления большого количества трафика, имеет смысл создать тестовую нагрузку, чтобы они заранее масштабировались. Вы также можете [связаться с Amazon](http://aws.amazon.com/articles/1636185810492479) чтобы они “прогрели” балансировщик нагрузки.\n-\t**Клиентские IP-адреса:** В общем, если серверы хотят знать истинные IP-адреса клиентов, балансировщики нагрузки должны каким-то образом пересылать эту информацию. CLB добавляет стандартный заголовок [X-Forwarded-For](https://en.wikipedia.org/wiki/X-Forwarded-For). При использовании CLB, как балансировщика нагрузки HTTP траффика, возможно таким образом получать клиентский IP-адрес.\n-\t**Использование балансировщиков нагрузки при развертывании:** Один из распространенных шаблонов заключается в замене инстансов в балансировщике нагрузки после развертывания нового стека на последнюю версию, сохранения работоспособности старого стека в течение одного или двух часов и либо возврата к старому стеку в случае проблем, либо его сноса.\n-   **Замена сертификатов с сохранением ARN:** Замена серверных сертификатов IAM может быть сложной, так как стандартная практика - загрузить новый и обновить все ресурсы с новым ARN. В любом случае, вы можете сохранить тот же ARN используя вызов `update-certificate` следующим путем:\n  1. Загрузить новый сертификат IAM с уникальным именем (например, fuzzy.com.new)\n  2. Переименовать существующий сертификат (например, fuzzy.com в fuzzy.com.expired)\n  3. Переименовать новый сертификат IAM на имя прошлого существующего сертификата (например, fuzzy.com.new в fuzzy.com)\n  4. Передернуть CLB/ALB Listener чтобы подтянуть изменения:\n      * ALB: Вызовите modify-listener с существующими параметрами ALB Listener\n\t  * CLB: Вызовите create-load-balancer-listeners с существующими параметрами CLB listener\n\n### Ошибки и ограничения, связанные с Load Balancer \n\n-\t❗CLB и ALBs не имеют **фиксированных публичных IP-адресов**, которые видны клиентам. Для большинства пользовательских приложений это не имеет значения, но ваши корпоративные клиенты могут этого захотеть. IP-адреса будут отличаться для каждого пользователя и непредсказуемо изменяться для одного клиента с течением времени (в пределах стандартных [диапазонов IP-адресов EC2](http://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html)). И точно так же никогда не резолвите имя CLB в IP и не указывайте его в качестве значения записи A - оно будет работать некоторое время, а затем сломается!\n-\t❗Некоторые веб-клиенты или обратные прокси-серверы кешируют DNS-запросы в течение длительного времени, что создает проблему для CLB и ALB, поскольку они меняют свои IP-адреса. Это означает, что через несколько минут, часов или дней, ваши клиенты перестанут работать, пока вы не отключите кэширование DNS. Следите за [настройками Java](http://docs.oracle.com/javase/8/docs/api/java/net/InetAddress.html) и обязательно [настройте их правильно](http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/java-dg-jvm-ttl.html). Другим примером может быть использование nginx в роли обратного прокси-сервера, который [обычно резолвит бэкенды только при запуске](https://www.jethrocarr.com/2013/11/02/nginx-reverse-proxies-and-dns-resolution/) (хотя есть [способ обойти эту проблему](https://tenzer.dk/nginx-with-dynamic-upstreams/)).\n-\t❗Пускай для вас не будет неожиданным, что IP-адреса будут перераспределяться между клиентами без длительного отстоя в пуле свободных адресов. Поэтому, как клиент, если вы кешируете IP-адрес и не используете SSL (для проверки сервера), вы можете получить не просто ошибки, а ответы от совершенно разных служб или компаний!\n-\t🔸Как оператор службы, работающей за CLB или ALB, последнее явление означает, что вы также можете видеть странные или ошибочные запросы клиентов других компаний. Это наиболее часто встречается у клиентов, использующих серверные API-интерфейсы (поскольку веб-браузеры обычно кешируют в течение ограниченного периода времени).\n-\t❗CLB и ALB требуется время для масштабирования, они не вытягивают внезапные всплески траффика. Таким образом, если вы ожидаете всплеск, вам необходимо “прогреть” балансировщик нагрузски постепенно посылая на него повышающиеся объемы траффика.\n-\t❗Тщательно настройте проверку работоспособности - если вы слишком агрессивны в отношении решения о том, когда удалять инстанс, и консервативны в отношении добавления его обратно в пул, служба, которую обслуживает ваш балансировщик нагрузки, может стать недоступной на несколько секунд или минут. Будьте крайне осторожны с этим, когда автоматическое масштабирование настроено на удаление инстансов, которые не прошли проверку балансировщика нагрузки.\n-\t❗CLB HTTPS listeners не поддерживают Индикацию имени сервера(Server Name Indication) (SNI). Если вам нужен SNI, вы можете обойти это ограничение используя сертификат с Subject Alternative Names (SAN) или используя TCP listener и терминируя SSL на бэкенде.\n-\t🔸 Существует ограничение на количество ALB, CLB и NLB на регион (отдельное для каждого). На конец 2017 года, ограничение по умолчанию для каждого - 20 на регион. Эти лимиты могут быть лекго повышены для ALB и CLB, но AWS довольно неохотно поднимает лимит для NLB.\n-\t🔸 Если вы используете сетевой балансировщик нагрузки(NLB) тогда клиенты EC2 не смогут подключиться к NLB, который находится в другом VPC (пиринг VPC) или VPN под управлением AWS, если только клиент EC2 не является экземпляром C5, i3.metal или M5. Для пиринга VPC оба VPC должны быть в одном и том же регионе. Тут описано [устранение неполадок](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-troubleshooting.html#target-not-in-service).\n\nКлассический балансировщик нагрузки(CLB)\n---\n\n### Основы CLB\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/elasticloadbalancing/classicloadbalancer/) ∙ [Руководство пользователя](https://aws.amazon.com/elasticloadbalancing/classicloadbalancer/developer-resources/) ∙ [ЧаВо](https://aws.amazon.com/elasticloadbalancing/classicloadbalancer/faqs/) ∙ [Расценки](https://aws.amazon.com/elasticloadbalancing/classicloadbalancer/pricing/)\n- Классические балансировщики нагрузки, ранее известные как Эластичные балансировщики нагрузки - это балансировщики нагрузки работающие по протоколам HTTP и TCP, которые управляются и масштабируются Amazon.\n\n### Советы по CLB\n\n-\t**Лучшие практики:** [Эта статья](http://aws.amazon.com/articles/1636185810492479) является обязательной к прочтению, если вы широко используете CLBs и содержит массу информации.\n\n### Ошибки и ограничения, связанные с CLB \n\n-\tВ общем и целом, CLB не такие “умные” как некоторые балансировщики нагрузки, и у них нет этих прикольных особенностей и детального контроля, который есть у традиционных железных балансировщиков нагрузки. В большинстве случаев, связанных с безсессионными приложениями или сеансами на основе файлов cookie через HTTP или терминацию SSL, они работают хорошо.\n-\t🔸По умолчанию, CLB откажет маршрутизировать траффик от балансировщика нагрузки в одной зоне доступности(AZ) на бэкенд инстанс в другой. В случае если последний инстанс в зоне доступности(AZ) будет недоступент - это [вызовет ошибку 503](http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/ts-elb-error-message.html#ts-elb-errorcodes-http503), даже есть живые инстансы есть в других зонах. Если у вас запущено менее двух бэкенд инстансов на зону доступности(AZ), вам почти наверняка необходимо [включить меж-зонную балансировку нагрузки](http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-disable-crosszone-lb.html#enable-cross-zone).\n-\t🔸Сложные правила для направления траффика не поддерживаются. Например, вы не можете направлять траффик на основании регулярных выражений в URL, как это делает HAProxy.\n-\t**Основные имена DNS:** Когда-то давным-давно, вы не могли назначать CLB на основную запись DNS (например example.com вместо foo.example.com) потому что требовалась A запись вместо CNAME. Теперь это стало возможным с использованием записи Route 53 alias напрямую указывающей на балансировщик нагрузки.\n-\t🔸CLB использует [HTTP keep-alives](https://en.wikipedia.org/wiki/HTTP_persistent_connection) на внутренней стороне. Это может привести к неожиданному эффекту: Запросы от разных клиентов, каждый из которых использует собственное TCP соединение на внешней стороне, могут дойти одним TCP соединением на внутренней стороне. Никогда не предполагайте, что несколько запросов на одном и том же TCP-соединении поступают от одного и того же клиента!\n-\t🔸 Траффик между CLB и бэкинстансами в одной подсети **обязательно** подчиняются правилам [Сетевого списка доступа(Network ACL)](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html), в то время как (траффик между EC2 в одной подсети - не проверяется на соответствие NACL). Если правило по умолчанию '0.0.0.0/0 ALLOW' удалено из NACL, назначенного на подсеть, правило разрешающее траффик на порты проверки на работоспособность и приложения должно быть добавлено.\n- По состоянию на 2016 год, CLB запущенный в VPCs не поддерживает IPv6 адресацию. CLB запущенный в окрущении EC2-Classic поддерживает IPv4 и IPv6 [с использованием DNS имени с префиксом \"dualstack\"](http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-internet-facing-load-balancers.html#internet-facing-ip-addresses).\n\nALB\n---\n\n### Основы ALB\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/elasticloadbalancing/applicationloadbalancer/) ∙ [Руководство пользователя](https://aws.amazon.com/elasticloadbalancing/applicationloadbalancer/developer-resources/) ∙ [ЧаВо](https://aws.amazon.com/elasticloadbalancing/applicationloadbalancer/faqs/) ∙ [Расценки](https://aws.amazon.com/elasticloadbalancing/applicationloadbalancer/pricing/)\n-\t🐥**Вебсокеты и HTTP/2** [теперь поддерживаются](https://aws.amazon.com/blogs/aws/new-aws-application-load-balancer/).\n-\t🐥**Интернет протокол версии 6 (IPv6)** [теперь поддерживается](https://aws.amazon.com/about-aws/whats-new/2017/01/announcing-internet-protocol-version-6-ipv6-support-for-elastic-load-balancing-in-amazon-virtual-private-cloud-vpc/).\n-\t🐥**Балансировка нагрузки по IP** [теперь поддерживается](https://aws.amazon.com/about-aws/whats-new/2017/08/elastic-load-balancing-application-load-balancer-now-supports-load-balancing-to-ip-addresses-as-targets-for-aws-and-on-premises-resources/).\n-\tДо появления программного балансировщика нагрузки(Application Load Balancer), вам было рекомендовано использовать TCP вместо HTTP, (как описано [тут](http://www.quora.com/When-will-Amazon-ELB-offer-SPDY-support)) и использовать [не понятный, но полезный протокол проксирования](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/enable-proxy-protocol.html) ([дополнительно можно прочесть тут](https://chrislea.com/2014/03/20/using-proxy-protocol-nginx/)), чтобы передавать IP-адреса клиентов через балансировщик нагрузки работающий по TCP.\n\n### Советы по ALB\n\n-\tИспользуйте ALB для маршрутизации запросов к сервисам, размещенным в общих кластерах с динамическим назначением портов. (таким как ECS или Mesos).\n-\tALB поддерживает [маршрутизацию на основе HTTP host](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#host-conditions) (посылаем HTTP запрос на “api.mydomain.com” -> {target-group-1}, “blog.mydomain.com” -> {target group 2}) также как и [маршрутизацию на основе HTTP пути](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#path-conditions) (посылаем HTTP запрос на “/api/&ast;” ->  {target-group-1}, “/blog/&ast;” -> {target group 2}).\n\n### Ошибки и ограничения, связанные с ALB\n\n-\t🔸ALB поддерживает HTTP/2 через HTTPS (не поддерживает HTTP/2 открытым текстом).\n-\t🔸ALB поддерживает HTTP/2 для внешних клиентов, а не для внутренних ресурсов (инстансов/контейнеров).\n-\tALB поддерживает маршрутизацию HTTP, но не поддерживает TCP маршрутизацию на основе номера порта.\n-\tИнстансы в таргет группах ALB должны иметь один, фиксированный порт для проверки работоспособности(health-check) (проверки работоспособности на уровне “EC2 инстанса”) или порт проверки работоспособности(health-check) для цели должен быть таким же, как и порт приложения (проверки работоспособности на уровне “приложения”) - вы не можете сконфигурировать порт проверки работоспособности для каждой цели, который бы отличался от порта приложения.\n-\tALB работает только при использовании VPC (и не доступно для EC2 Classic)\n-\tЕсли в таргет группе нет живой цели, все запросы направляются ко всем членам таргет группы. Например, если вы настроили листенер на таргет группу, содержащую один сервис с долгой фазой инициализации(во время которой, все проверки на работоспособность не пройдут), запросы все равно будут достигать сервиса, несмотря на то, что он все еще загружается.\n- 📜 Кроме того ALB [теперь поддерживает SNI(расширение TLS позволяющее передавать имя хоста с которым он хочет соединиться)](https://aws.amazon.com/about-aws/whats-new/2017/10/elastic-load-balancing-application-load-balancers-now-support-multiple-ssl-certificates-and-smart-certificate-selection-using-server-name-indication-sni/), однако поддерживается только 25 HTTPS сертификатов на балансировщик нагрузки. Это ограничение не описано [здесь](http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-limits.html), так что возможно, что это изменится.\n\nElastic Beanstalk\n----------------\n\n### Основы Elastic Beanstalk\n- 📒 [Домашняя страница](https://aws.amazon.com/elasticbeanstalk/) ∙ [Руководство разработчика](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/Welcome.html) ∙ [ЧаВо](https://aws.amazon.com/elasticbeanstalk/faqs/) ∙ [Расценки](https://aws.amazon.com/elasticbeanstalk/pricing/)\n- **EB** (Elastic Beanstalk) - это PaaS (Платформа как сервис) которая помогает разработчикам создавать, развертывать и масштабировать веб-приложения\n- EB управляет развертыванием, настройкой, выделением ресурсов, балансировкой нагрузки, автоматическим масштабированием, мониторингом и ведением логов.\n- EB создает ресурсы AWS от вашего имени, но вы сохраняете полный доступ и контроль над основными ресурсами\n- 💸 Использование EB бесплатно, но вы все равно будете платить полную стоимость базовых ресурсов AWS, созданных EB.\n\n### Советы по Elastic Beanstalk\n- Чтобы ускорить развертывание перед запуском или на этапе разработки, отключите проверки работоспособности и установите `Deployment policy` значение `All at once`\n- Если у вас есть конфигурация, которую вы хотите использовать повторно для нескольких приложений EB, вы можете сохранить текущую конфигурацию, используя `eb config save --cfg myEBConfig`\n- По умолчанию, в EB нет аварийных оповещений. Вам необходимо добавить их самостоятельно, в соответствии с метриками, которые вы мониторите. \n- По умолчанию, EB не включает [управляемые обновления платформы](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-platform-update-managed.html?icmpid=docs_elasticbeanstalk_console). Включите их в настройках, чтобы EB автоматически применял обновления в заранее установленный период обслуживания\n\n### Ошибки и ограничения, связанные с Elastic Beanstalk\n- 🔸 Не редактируйте конфигурационные файлы [apache|nginx] вручную на инстансах ec2, так как они будут перезаписаны при каждом развертывании (вместо этого используйте [ebextensions](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions.html))\n- 🔸 После создания среды EB, больше не представляется возможным изменения тэга `Name`\n- 🔸 EB иногда помещает в карантин инстансы, которые вызывают многократные проблемы развертывания. Несмотря на карантин, EB все равно будет развертываться на них при последующих развертываниях. Чтобы предотвратить такое поведение, указанные инстансы необходимо удалить (или устранить проблему)\n- Загрузка файлов ограничена 10MB в большинстве конфигураций eb по умолчанию, обновите [конфигурационный файл nginx](https://stackoverflow.com/questions/18908426/increasing-client-max-body-size-in-nginx-conf-on-aws-elastic-beanstalk) чтобы исправить это\n- Если вы редактируете `.elasticbeanstalk/saved_configs/`, знайте, что он не синхронизируется с конфигураций среды EB. Вам необходимо вручную подтянуть настройки и сохранить их для применения изменений.\n\nElastic IPs\n-----------\n\n### Основы Elastic IP\n\n-\t📒 [Документация](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) ∙ [ЧаВо](https://aws.amazon.com/ec2/faqs/#Elastic_IP) ∙ [Расценки](https://aws.amazon.com/ec2/pricing/on-demand/#Elastic_IP_Addresses)\n-\t**Elastic IPs** - это статичные IP адреса, которые вы можете арендовать у AWS и назначить инстансам EC2.\n\n### Советы по Elastic IP\n\n-\t🔹**Предпочтите балансировщики нагрузки использованию Elastic IP:** Для развертываний на одном инстансе, вы можете просто назначить Elastic IP данному инстансу, назначить DNS имя данному адресу и считать это все вашим развертыванием. Однако в большинстве случаев вам стоило бы развернуть [балансировщик нагрузки](#балансировщики-нагрузкиload-balancers) вместо этого:\n\t-\tЛегко добавлять и удалять инстансы из группы балансировщика нагрузки. Кроме того, быстрее добавлять или удалять инстансы из группы балансировщика нагрузки, чем переназначать эластичный IP-адрес.\n\t-\tУдобнее указывать записи DNS на балансировщик нагрузки, а не указывать их на конкретные IP-адреса, которыми вы управляете вручную. Можно также использовать алиасы Route 53, которыми проще управлять и изменять.\n\t-\tНо в некоторых ситуациях вам необходимо закреплять IP-адреса инстансов EC2 и управлять ими, например, если клиенту нужен фиксированный IP-адрес. Эти ситуации требуют эластичных IP-адресов.\n-\tСуществует ограничение в 5 эластичных IP-адресов на аккаунт. Существует возможность [запросить больше](https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-elastic-ips-ec2-classic).\n-\tЕсли эластичных IP-адрес не назначен действующему ресурсу, существует небольшая [почасовая оплата](https://aws.amazon.com/ec2/pricing/on-demand/#Elastic_IP_Addresses).\n-\tВам не надо платить [дополнительно](https://aws.amazon.com/ec2/pricing/on-demand/#Elastic_IP_Addresses) за использование эластичного IP-адреса, пока вы им пользуетесь. Однако во время простоя есть небольшие издержки, что является механизмом противодействия захвату большого количества IP адресов.\n\n### Ошибки и ограничения, связанные с Elastic IP \n\n-\t🔸[Официально нет никакой возможности](https://forums.aws.amazon.com/thread.jspa?threadID=171550) получить последовательный блок IP адресов, что было бы неплохо при раздаче адресов внешним пользователям. Однако вам может повезти и вы получите адрес, которые являеются частью одного CIDR блока. Если вам это действительно важно, вы можете [принести свои собственные IP](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html), что является более сложным, нежели то, что рассматривается в этом руководстве.\n\nGlacier\n-------\n\n### Основы Glacier\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/glacier/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/amazonglacier/latest/dev/) ∙ [ЧаВо](https://aws.amazon.com/glacier/faqs/) ∙ [Расценки](https://aws.amazon.com/glacier/pricing/)\n-\t**Glacier** - это более дешевая альтернатива S3, для тех случаев, когда доступ к данным необходим редко, как например для архивирования.\n-\tЭто полезно только для данных, к которым редко обращаются. Обычно выполнение запроса извлечения занимает [3-5 часов] (https://aws.amazon.com/glacier/faqs/#dataretrievals).\n-\tAWS [официально не разглашает](https://en.wikipedia.org/wiki/Amazon_Glacier#Storage) устройство хранения используемого Glacier; возможно это медленные жесткие диски или даже магнитные ленты.\n-\tAWS выпустил еще более экономичное хранилище, называемое [Glacier Deep Archive](https://aws.amazon.com/blogs/aws/new-amazon-s3-storage-class-glacier-deep-archive/), которое предлагает время извлечения ~12 часов, но стоит примерно 1000 долларов за петабайт в месяц.\n\n### Советы по Glacier\n\n-\tВы можете физически [отправить по почте](https://aws.amazon.com/blogs/aws/send-us-that-data/) ваши данные в Amazon, чтобы поместить в Glacier, на жестком диске USB или eSATA.\n\n### Ошибки и ограничения, связанные с Glacier\n\n-\t🔸Получение файлов с Glacier происходит очень-очень медленно (обычно 3-5 часов и более).\n-\t🔸Из-за фиксированных накладных расходов на файл (вы платите за операции PUT или GET), загрузка и выгрузка множества маленьких файлов на / в Glacier может быть очень дорогой. Также необходимо учитывать хранение метаданных в размере 32кб дополнительно на файл. Следовательно, архивировать файлы перед загрузкой - хорошая идея.\n-\t💸Помните о стоимости за каждый объект архивирования данных S3 в Glacier. [Это стоит $ 0,05 за 1000 запросов](https://aws.amazon.com/s3/pricing/). Если у вас есть большое количество объектов S3 относительно небольшого размера, [потребуется время, чтобы достичь точки безубыточности относительно хранения в S3](https://alestic.com/2012/12/s3-glacier-costs/) (первоначальная стоимость архивирования по сравнению с более низкой ценой хранения).\n\nRDS\n---\n\n### Основы RDS\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/rds/) ∙ [Руководство пользователя](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/) ∙ [ЧаВо](https://aws.amazon.com/rds/faqs/) ∙ [Расценки](https://aws.amazon.com/rds/pricing/) (также смотрите [ec2instances.info/rds/](http://www.ec2instances.info/rds/)\\)\n-\t**RDS** - это управляемый сервис реляционных баз данных, позволяющий вам разворачивать и масштабировать базы данных намного проще. Он поддерживает [Oracle](https://aws.amazon.com/rds/oracle/), [Microsoft SQL Server](https://aws.amazon.com/rds/sqlserver/), [PostgreSQL](https://aws.amazon.com/rds/postgresql/), [MySQL](https://aws.amazon.com/rds/mysql/), [MariaDB](https://aws.amazon.com/rds/mariadb/) и собственную СУБД AWS [Aurora](https://aws.amazon.com/rds/aurora/).\n-\tRDS из коробки предлагает поддержку [высокой доступности и отказоустойчивости](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZ.html) для ваших баз данных.\n\n### Советы по RDS\n\n-\tЕсли вы ищете управляемые сервис с удобством RDS для других хранилищ данных, таких как MongoDB или Cassandra, возможно вам стоит предпочесть сторонние сервисы от провайдеров, таких как [Compose](https://www.compose.com/) или [InstaClustr](https://www.instaclustr.com/).\n-\t🔹Обязательно создайте новую [группу параметров](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html) и группу опций для своей базы данных, поскольку группа параметров по умолчанию не допускает динамических изменений конфигурации.\n-\tRDS инстансы запускаются с часовым поясом UTC по умолчанию. Если необходимо, можно [сменить часовой пояс на другой](https://aws.amazon.com/premiumsupport/knowledge-center/rds-change-time-zone/).\n\n### Ошибки и ограничения, связанные с RDS\n\n-\t⏱RDS инстансы запускаются на томах EBS (либо общего назначения(general-purpose) либо с выделенным IOPS(provisioned IOPS)) и, следовательно, ограничены производительностью EBS.\n-\t🔸Проверьте, какие функции базы данных вам нужны, так как не все, что вам нужно, доступно в RDS. Например, если вы используете Postgres, проверьте список [поддерживаемых функций и расширений](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#SQLServer.Concepts.General.FeatureSupport). Если необходимые вам функции не поддерживаются RDS, вам придется развернуть базу данных самостоятельно.\n-\t🔸Если вы используете поддержку отказоустойчивости, предлагаемую RDS, помните, что она основана на изменениях DNS, и убедитесь, что ваш клиент реагирует на эти изменения соответствующим образом. Это особенно важно для Java, учитывая то, как TTL его DNS-резолвера настроен по умолчанию(http://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-jvm-ttl.html).\n-\t🔸**Миграция баз данных в RDS:** При импорте вашей базы данных в RDS убедитесь, что вы учитываете настройки окна обслуживания. Если резервное копирование выполняется одновременно с импортом, импорт может занять значительно больше времени, чем вы ожидали.\n-\t[Размеры баз данных ограничены](https://aws.amazon.com/about-aws/whats-new/2015/06/amazon-rds-increases-storage-limits-to-6TB-for-piops-and-gp2/) **6TB** для всех СУБД, за исключением SQL Server у которого лимит - **4TB** и Aurora, которая поддерживает базы данных до  **64TB**.\n\nRDS MySQL и MariaDB\n---------------------\n\n### Основы RDS MySQL и MariaDB\n\n-      RDS предлагает MySQL версий 5.5, 5.6, 5.7 и 5.8.\n-      RDS предлагает MariaDB версий 10.0, 10.1, 10.2 и 10.3.\n\n### Советы по RDS MySQL и MariaDB\n\n-\tMySQL RDS позволяет доступ к [бинарным логам](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_LogAccess.Concepts.MySQL.html#USER_LogAccess.MySQL.BinaryFormat).\n-\tИнстансы MySQL при развертывании в нескольких зонах доступности прозрачно реплицируют данные между зонами доступности используя DRBD. Автоматическое резервное копирование инстансов при развертывании в нескольких зонах доступности [запускается на резервном инстансе](https://www.percona.com/live/mysql-conference-2014/sessions/rds-mysql-tips-patterns-and-common-pitfalls) чтобы убрать возможность всплесков на основном сервере.\n-\t🔸**Performance Schema:** Хотя [Performance Schema](http://dev.mysql.com/doc/refman/en/performance-schema.html) включена по умолчанию в MySQL 5.6.6 и в более поздних версиях, она выключена по умолчанию в RDS. Если вы хотите включить Performance Schema, потребуется перезагрузка инстанса RDS.\n-\t🔸**MySQL или MariaDB или Aurora:** Если вы предпочитаете СУБД в стиле MySQL, но начинаете что-то новое, вам стоило бы рассмотреть Aurora и MariaDB. **Aurora** имеет повышенную доступонсть и являюется решением следующего поколения. Тем не менее Aurora [может и не быть](http://blog.takipi.com/benchmarking-aurora-vs-mysql-is-amazons-new-db-really-5x-faster/) намного быстрее MySQL для конкретных рабочих нагрузок. **MariaDB** - современный [комьюнити форк](https://en.wikipedia.org/wiki/MariaDB) MySQL, [похоже, что имеет преимущества над MySQL](http://cloudacademy.com/blog/mariadb-vs-mysql-aws-rds/) для многих целей, поддерживается RDS.\n\n### Ошибки и ограничения, связанные с  RDS MySQL и MariaDB\n\n-\t🔸**Никаких SUPER привилегий** RDS предоставляет несколько [хранимых процедур](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.MySQL.SQLRef.html) для выполнения некоторых задач, которым требуются SUPER привилегии, например запуск и остановка репликации.\n-\t🔸Вы можете реплицировать на инстансы MySQL, не относящиеся к RDS, но [репликация на эти инстансы будет прерываться во время аварийного переключения между зонами доступности](https://www.percona.com/live/mysql-conference-2014/sessions/rds-mysql-tips-patterns-and-common-pitfalls).\n-\t🔸Отсуствует возможность ручной смены мастера на репликах, так что их все необходимо будет пересоздать после аварийного переключения мастера.\n-\t🔸Большинство глобальных опций доступно только в [группах параметров БД(DB parameter groups)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html). Некоторые переменные, которые были введены в более поздних точечных выпусках MySQL, такие как [avoid_temporal_upgrade](https://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_avoid_temporal_upgrade) в MySQL 5.6.24, не доступны в группах параметров для версии 5.6.х в RDS и их использование требует обновления на MySQL 5.7.x.\n-\t🔸Функции RDS, такие как восстановление на конкретную точку времени и восстановление со снапшота не поддерживаются для таблиц MyISAM. Убедитесь, что вы заблокировали и очистили каждую таблицу MyISAM перед выполнением снапшота или операции резервного копирования, чтобы обеспечить консистентность.\n\nRDS PostgreSQL\n--------------\n\n### Основы RDS PostgreSQL\n\n- RDS предлагает PostgreSQL 9.3, 9.4, 9.5, 9.6 и 10.\n\n### Советы по RDS PostgreSQL\n\n- Недавно была добавлена поддержка логической репликации, [как публикации, так и подписки](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#PostgreSQL.Concepts.General.version104).\n- Поддерживает довольно большой диапазон родных [расширений](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#PostgreSQL.Concepts.General.FeatureSupport.Extensions).\n- RDS PostgreSQL 10 поддерживает собственный партишенинг и большинство основных функций и настроек.\n- Поддерживает соединение через SSL.\n- Поддерживает восстановление между зонами доступности и к конкретной точке во времени.\n\n### Ошибки и ограничения, связанные с  RDS PostgreSQL\n- Отсутствют суперпользовательские привилегии. RDS предоставляет роль `rds_superuser`, которая может выполнять большинство из необходимых операций, однако имеются некоторые ограничения.\n- Добавление некоторых важных функций запаздывает по сравнению с PostgreSQL.\n- По умолчанию RDS поставляется с SSD общего назначения, если вам необходима лучшая производительность, вам необходимо выбрать SSD с выделенными IOPS.\n- Вы не можете использовать RDS, как реплику с внешнего сервера без использования логической репликации.\n- Существуют параметры, которые нельзя изменить, и большинство параметров, которые можно изменить, можно изменить только с помощью групп параметров базы данных.\n- Ввиду того, что у вас нет доступа на хост - сложнее решать проблемы производительности.\n- Убедитесь, что все необходимые [расширения](https://www.postgresql.org/docs/current/static/view-pg-available-extensions.html) доступны. Если вы используете расширение, которого нет в списке, вам нужно будет найти обходной варант или развернуть собственную базу данных в EC2.\n- Многие утилиты и элементы обслуживания Postgres требуют доступа из командной строки, что обычно можно выполнить с помощью внешнего сервера ec2.\n\nRDS SQL Server\n--------------\n\n### Основы RDS SQL Server\n\n-\t[RDS предлагает SQL Server 2008 R2, 2012, 2014, 2016 и 2017](https://aws.amazon.com/rds/sqlserver/) включая Express, Web, Standard и Enterprise.\n\n### Советы по RDS SQL Server\n\n-\tНедавно добавленная поддержка [резервныого копирования и восстановления в/из S3](https://www.brentozar.com/archive/2016/07/holy-cow-amazon-rds-sql-server-just-changed-everything/) делает привлекательным [вариантом восстановления в случае аварии](https://aws.amazon.com/blogs/aws/amazon-rds-for-sql-server-support-for-native-backuprestore-to-amazon-s3/) для локальных серверов.\n\n### Ошибки и ограничения, связанные с  RDS SQL Server\n\n-\t🔸Пользователь имеет только права db_owner для каждой базы в инстансе.\n-\t🔸Хранилище не может быть расширено для существующих баз данных. Если вам необходимо больше места, вам необходимо восстановить вашу базу данных на новом инстансе с большим хранилищем.\n-\t🔸**16TB** - ограничение максимального размера базы данных для всех версий, кроме Express. Также есть минимальное ограничение размера, 20GB для Web и Express, 200GB для Standard и Enterprise.\n-\t🔸Есть ограничение в [30 баз данных на инстанс](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_SQLServer.html)\n\nRDS Aurora\n----------\n### Основы RDS Aurora\nAurora - это облачная служба баз данных, предназначенная для предоставления распределенной, отказоустойчивой реляционной базы данных с самовосстанавливающимся хранилищем и автоматическим масштабированием до 64 ТБ. В настоящее время она выпускается в двух версиях: совместимая с MySQL и совместимая с PostgreSQL.\n\nRDS Aurora MySQL\n----------------\n\n### Основы RDS Aurora MySQL\n\n-\tПроприетарный форк MySQL от Amazon, созданный для масштабирования высококонкурентных рабочих нагрузок. В общем говоря, производительность отдельных запросов в Aurora не особенно повысится относительно MySQL и MariaDB, но Aurora создана для поддержки этого уровня производительности при обеспечении запуска гораздо большего количества запросов одновременно, чем может выдержать эквивалентный сервер MySQL или MariaDB.\n-\t[Известные новые функции](http://www.slideshare.net/AmazonWebServices/amazon-aurora-amazons-new-relational-database-engine) включают в себя:\n\t-\tЖурнально-структурированное хранилище вместо B-tree для повышения производительности записи.\n\t-\tНезависимый буферный пул, так что инстансы баз данных могут быть перезапущены без очистки буфера.\n\t-\tБазовое физическое хранилище представляет собой специализированный массив SSD, который автоматически поддерживает 6 копий ваших данных в 3 зонах доступности(AZ).\n\t-\tРеплики только-для-чтения в Aurora используют один уровень хранения с мастером, что существенно снижает лаг реплики, устраняет необходимость записи и отправки бинарных логов для репликации с мастера, и позволяет производить аварийное переключение с мастера на реплику без потерь данных. Мастер и реплики для чтения, которые используют одно хранилище, совместно называются **кластер Aurora**. Реплики могут размещаться в масштабах до [5 регионов](https://aws.amazon.com/about-aws/whats-new/2018/09/amazon-aurora-databases-support-up-to-five-cross-region-read-replicas/).\n\n### Советы по RDS Aurora MySQL\n\n-\tЧтобы воспользоваться преимуществами более высокого уровня параллелизма в Aurora, приложения должны быть настроены с большими пулами соединений с базой данных и выполнять как можно больше запросов одновременно. Например, сервера Aurora тестировались в целях получения более высокой производительности на некоторых рабочих нагрузках OLTP с примерно [5,000 соединениями](http://www.slideshare.net/AmazonWebServices/amazon-aurora-amazons-new-relational-database-engine/31).\n-\t[Aurora прекрасно масштабируется с несколькими CPU](https://www.percona.com/blog/2016/05/26/aws-aurora-benchmarking-part-2/) и может потребовать высокий класс инстанса для оптимальной производительности.\n-\tПростейшим путем миграции на Aurora является восстановление базы данных из снапшота с MySQL 5.6 или 5.7. Следующим простейшим методом является восстановление дампа с MySQL совместимой СУБД, такой как MariaDB. Для [миграции с малым прерыванием работы](https://aws.amazon.com/blogs/aws/amazon-aurora-update-spatial-indexing-and-zero-downtime-patching/) с других MySQL-совместимых СУБД, вы можете настроить инстанс Aurora, как реплику вашей существующей СУБД. Если же ни один из этих вариантов не подошел, Amazon предлагает платный сервис миграции данных.\n-\tВы можете реплицировать данные [с кластера Aurora в MySQL или на другоой кластер Aurora](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Aurora.Overview.Replication.MySQLReplication.html). Это требует включения опции бинарного логирования и работает не так, как родная репликация Aurora.\n-\tТак как реплики Aurora являются [аналогом распределенного по различным зонам доступности резервного копирования](http://stackoverflow.com/a/32428651/129052) и могут быть сконфигурированы как цели для аварийного переключения без потери данных, существует малое количество сценариев, в которых вам потребуется создание распределенного по зонам доступности инстанса Aurora.\n\n### Ошибки и ограничения, связанные с  RDS Aurora MySQL\n\n- 🔸[Aurora 1.x основана на MySQL 5.6.x](https://news.ycombinator.com/item?id=12415693) с некоторой подборкой более поздних функций MySQL. В ней отсутствуют большинство функций 5.7, а также некоторые онлайн-функции DDL, представленные в 5.6.17.\n- 🔸[Aurora 2.x основана на MySQL 5.7.x](https://aws.amazon.com/about-aws/whats-new/2018/02/amazon-aurora-is-compatible-with-mysql-5-7/)\n- Aurora не поддерживает транзакции GTID как в 5.6/Aurora 1.x, так и в 5.7/Aurora 2.x.\n- Максимальный размер кластера Aurora - 64 TB\n\nRDS Aurora PostgreSQL\n---------------------\n\n### Основы RDS Aurora PostgreSQL\n\n- Проприетарный форк PostgreSQL от Amazon, созданный для масштабирования высококонкурентных рабочих нагрузок, но с сохранением легкости пользования. На текущий момент основана на PostgreSQL 9.6.\n- Высокая пропускная способность (вплоть до трехкратного превышения показателей на том же оборудовании).\n- Автоматическое масштабирование хранилища инкрементами по 10GB до 64TB.\n- Реплики для чтения с низкой задержкой, которые используют совместно с мастером уровень хранилища, что серьезно снижает лаг реплики.\n- Восстановление на любую точку времени.\n- Быстрые снапшоты баз данных.\n\n### Советы по RDS Aurora PostgreSQL\n- Aurora Postgres по умолчанию предполагает утилизацию большого количества соединения, поэтому пул соединений необходимо настроить соотвественным образом.\n- Так как Aurora основана на PostgreSQL 9.6, в нем отсутствуют такие функции, как декларативное разбиение или логическая репликация.\n\n### Ошибки и ограничения, связанные с RDS Aurora PostgreSQL\n\n- Aurora PostgreSQL отстает от обычного RDS, когда дело доходит до доступных версий, поэтому, если вам нужны функции из последней версии PostgreSQL, вам может быть лучше использовать обычный RDS.\n- Патчинг и исправление багов является отдельным от PostgreSQL.\n\nElastiCache\n-----------\n\n### Основы ElastiCache\n\n- 📒 [Домашняя страница](https://aws.amazon.com/elasticache/) ∙ [Руководство пользователя для Redis](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/index.html) ∙ [Руководство пользователя для Memcached](https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/index.html) ∙\n  [ЧаВо](https://aws.amazon.com/elasticache/faqs/) ∙\n  [Расценки](https://aws.amazon.com/elasticache/pricing/)\n- **ElastiCache** это управляемый сервис кэширования в памяти, который может быть использован для хранения временных данных в быстром кэше в памяти, обычно в целях того, чтобы избежать одинаковых вычислительных операций в то время, как данные могут быть взяты снова. \n- Он поддерживает [Memcached](https://memcached.org) и\n  [Redis](https://redis.io) - открытое программное обеспечение для кэширования в памяти, они оба используют свои собственные API.\n- Основное преимущество заключается в том, что AWS заботится о запуске, исправлении и оптимизации нод кэширования для вас, так что вам просто нужно запустить кластер и настроить его эндпоинт в вашем приложении, в то время как AWS возьмет на себя большую часть работы по запуску нод кэширования.\n   \n### Советы по ElastiCache\n\n- Выберите\n  [движок](http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/SelectEngine.html), конфигурацию кластера и [тип инстанса] http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheNodes.SelectSize.html) исходя из потребностей вашего приложения. Документация подробно объясняет плюсы, минусы и ограничения каждого механизма, чтобы помочь вам выбрать наиболее подходящий для вашего приложения. В двух словах, Redis предпочтительнее для хранения более сложных структур данных, в то время как Memcached - это просто хранилище ключ/значение. Простота Memcached позволяет ему быть немного быстрее и позволяет масштабировать его при необходимости, но Redis имеет больше функций, которые вы можете использовать в своем приложении.\n- Для Memcached AWS предоставляет расширенные SDK для определенных языков программирования, которые реализуют [автообнаружение](http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/AutoDiscovery.html), функцию, не доступную в обычных библиотеках клиента memcached.\n\n### Ошибки и ограничения, связанные с ElastiCache\n\n- Поскольку в некоторых случаях изменение кластеров кэша может иметь некоторые ограничения, например, для целей [масштабирования](http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Scaling.html), это может стать проблемой, если они были запущены с использованием CloudFormation в стеке, который также содержит другие ресурсы, и вам действительно необходимо изменить кэш.Во избежание перевода стеков CloudFormation в состояние без возможности обновления, рекомендуется запускать кластеры ElastiCache (как и любой другой ресурс с аналогичными ограничениями) в выделенных стеках, которые можно полностью заменить новыми стеками, имеющими желаемую конфигурацию.\n\n\nDynamoDB\n--------\n\n### Основы DynamoDB\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/dynamodb/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/) ∙ [ЧаВо](https://aws.amazon.com/dynamodb/faqs/) ∙ [Расценки](https://aws.amazon.com/dynamodb/pricing/)\n-\t**DynamoDB** - это [NoSQL](https://en.wikipedia.org/wiki/NoSQL) база данных, которая фокусируется на скорости, гибкости и масштабируемости.\n-\tDynamoDB оплачивается на основе комбинации пропускной способности и объема хранения данных.\n\n### Альтернативы DynamoDB и привязки\n\n-\t⛓ В отличие от технологий, лежащих в основе многих других продуктов Amazon, DynamoDB является проприетарным продуктом AWS без совместимой с интерфейсом альтернативы, доступной в качестве проекта с открытым исходным кодом.Если вы тесно связываете свое приложение с его API и набором функций, его замена потребует значительных усилий.\n-\tНаиболее часто используемая альтернатива DynamoDB - [Cassandra](http://cassandra.apache.org/).\n\n### Советы по DynamoDB\n\n-\tСуществует [**локальная версия DynamoDB**](https://aws.amazon.com/blogs/aws/dynamodb-local-for-desktop-development/) предоставляемая для использования в разработке.\n-\t[DynamoDB Streams](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) предоставляет упорядоченный поток изменений в таблице. Используйте его для репликации, резервного копирования или извлечения событий из данных.\n-\tDynamoDB может использоваться [в качестве простой службы блокировки](https://gist.github.com/ryandotsmith/c95fd21fab91b0823328).\n-\tИндексация DynamoDB может включать **первичные ключи**, которые могут быть либо хеш-ключом с одним атрибутом, либо диапазоном составного хеш-ключа. Вы также можете запросить атрибуты не первичного ключа, используя [**вторичные индексы**] (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.html).\n-\t**Типы данных:** DynamoDB поддерживает три [типа данных](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.DataTypes.html) – **число**, **строка**, и **двоичные(binary)** – как в скалярных, так и в многозначных множествах. DynamoDB также может поддерживать [**JSON**](https://aws.amazon.com/blogs/aws/dynamodb-update-json-and-more/).\n-\tПо состоянию на конец 2017 года, DynamoDB поддерживает как [глобальные таблицы](https://aws.amazon.com/dynamodb/global-tables/), так и [функциональность резервного копирования и восстановления](https://aws.amazon.com/dynamodb/backup-restore/).\n\n### Ошибки и ограничения, связанные с DynamoDB \n\n-\t🔸 DynamoDB не предоставляет простой способ массовой загрузки данных(это возможно через [Data Pipeline](http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-importexport-ddb-part1.html)) и моет привести к [печальным последствиям](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html#GuidelinesForTables.AvoidExcessivePTIncreases). Поскольку для обновления существующих или создания новых строк необходимо использовать обычные служебные API-интерфейсы, обычно для ускорения импорта временно увеличивают пропускную способность записи в целевой таблице. Но когда емкость записи таблицы увеличивается, DynamoDB может выполнить необратимое разделение партиций, лежащих в основе таблицы, распределяя полную емкость таблицы равномерно между новыми таблицами. Позднее, когда емкость будет снижена, емкость каждой партиции также будет снижена, однако количество партиций останется тем же, что приведет к снижению емкости каждой партиции. Это приводит таблицу в состояние, когда хотспоты могут перегрузить отдельную партицию.\n-\t🔸 Важно удостовериться, что [ресурсные лимиты](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-data-types) DynamoDB совместимы с вашим набором данных и рабочей нагрузкой. Например, максимальный размер значения, которое может быть добавлено в таблицу DynamoDB - 400 KB (большие данные могут храниться в S3 и хранить URL в DynamoDB).\n-\t🔸 Работа с **данными временного ряда** в DynamoDB может быть сложной задачей. Глобальный вторичный индекс совместно с понижающейся выборкой временных меток может выступать в роли возможного решения, как описано [тут](https://blogs.aws.amazon.com/bigdata/post/Tx3KPZDXIBJEQ4B/Scaling-Writes-on-Amazon-DynamoDB-Tables-with-Global-Secondary-Indexes).\n-\t🔸 DynamoDB не [позволяет](https://forums.aws.amazon.com/thread.jspa?threadID=90137) пустой строке быть значением атрибута. Наиболее часто используемый способ обхода - использовать заменяемое значение взамен пустого поля.\n-\t🔸 Когда настраиваешь [гранулированные политики доступа](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/specifying-conditions.html) к таблицам DynamoDB, убедись, что включил их вторичные индексы в политику.\n\n\nECS\n---\n\n### Основы ECS\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/ecs/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/) ∙ [ЧаВо](https://aws.amazon.com/ecs/faqs/) ∙ [Расценки](https://aws.amazon.com/ecs/pricing/)\n-\t**ECS** (EC2 Container Service) это относительно новый сервис (запущен в конце 2014 года), который управляет кластерами сервисов, развернутых через Docker.\n-\tПосмотрите раздел [Контейнера и AWS](#контейнера-и-aws) для получения дополнительной информации о контейнерах.\n-\tПрименение ECS растет, особенно в компаниях, использующих микросервисы.\n-\tСамостоятельное развертывание Docker напрямую на машинах в EC2 также остается одним из основных подходов использования Docker в AWS. Использование ECS не обязательно и ECS пока не является доминантным способом использования Docker в AWS.\n-\tТакже возможно использования [Elastic Beanstalk с Docker](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_docker.html), что является целесообразным если вы уже используете Elastic Beanstalk.\n-\tИспользование Docker может изменить способ развертывания ваших сервисов в EC2 или Elastic Beanstalk, но это не меняет радикально то, как используется большинство других служб.\n-\t[ECR](https://aws.amazon.com/ecr/) (EC2 Container Registry) - это управляемый Amazon реестр образов Docker. Хотя его использование проще, нежели развертывание своего реестра, у него отсуствуют некоторые особенности, которые могут потребоваться некоторым пользователям: \n\t-\tНе поддерживается межрегиональная репликация образов.\n\t\t-\tЕсли вам необходимо быстрое развертывание больших образов на весь флот инстансов, вам необходимо положить ваш образ в региональный реестр.\n\t-\tНе поддерживает пользовательские домены / сертификаты. \n-\tРаботоспособность контейнеров мониторится  [CLB](#классический-балансировщик-нагрузкиclb) или [ALB](#alb). Они также используются для доступа к контейнеризированным сервисам. При использовании ALB вам не нужно обрабатывать конфликты портов (то есть сервисы, предоставляющие один и тот же порт на одном и том же хосте), поскольку целевые группы ALB могут быть напрямую связаны со службами на основе ECS.\n-\t[Руководство автостопщика по AWS ECS и Docker](http://start.jcolemorrison.com/the-hitchhikers-guide-to-aws-ecs-and-docker/) написанное J. Cole Morrison является великолепной статьей по представлению концепций AWS ECS.\n\n\n\n### Советы по ECS\n\n-\t**Драйверы логов(коллекторы):** ECS поддерживает множество драйверов логов (awslogs, splunk, fluentd, syslog, json, ... ). Используйте [`awslogs`](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_awslogs.html) для CloudWatch (сначала убедитесь, что группа для логов создана). [Такие драйвера, как fluentd по умолчанию выключены](https://github.com/aws/amazon-ecs-agent/issues/535). Вы можете установить агента и включить драйвер путем добавления `ECS_AVAILABLE_LOGGING_DRIVERS='[\"awslogs\",\"fluentd\"]'` в `/etc/ecs/ecs.config`.\n-\t[Этот блог от Convox](https://convox.com/blog/ecs-challenges) (и [комментарии](https://news.ycombinator.com/item?id=11598058)) перечисляют ряд общих проблем с ECS по состоянию на начало 2016 года.\n- Можно оптимизировать очистку диска на ECS. По умолчанию неиспользуемые контейнеры удаляются через 3 часа, а неиспользуемые образы - через 30 минут. Эти настройки можно изменить путем добаления `ECS_ENGINE_TASK_CLEANUP_WAIT_DURATION=10m` и `ECS_IMAGE_CLEANUP_INTERVAL=10m` в `/etc/ecs/ecs.config`. [Больше информации по оптимизации очистки диска в ECS](https://aws.amazon.com/blogs/compute/optimizing-disk-usage-on-amazon-ecs/).\n\n### Альтернативы ECS и привязки\n\n-\t[Kubernetes](https://kubernetes.io): Обширная контейнерная платформа. Доступна как сервис на Google Cloud (https://cloud.google.com/container-engine/) и AWS (https://tectonic.com/). У AWS есть руководство по быстрому старту Kubernetes (https://aws.amazon.com/quickstart/architecture/heptio-kubernetes/) разработанное совместно с Heptio.\n-\t[Nomad](https://www.nomadproject.io/): Оркестратор/Планировщик, тесно связанный со стэком Hashicorp (Consul, Vault и т.д.).\n\n🚧 [*Пожалуйста помогите дополнить этот незавершенный раздел*](CONTRIBUTING.md)\n\nEKS\n---\n\n### Основы EKS\n-\t📒 [Домашняя страница](https://aws.amazon.com/eks/) ∙ [Руководство пользователя](http://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) ∙ [ЧаВо](https://aws.amazon.com/eks/faq/) ∙ [Расценки](https://aws.amazon.com/eks/pricing/)\n- EKS (Elastic Kubernetes Service) - это новый сервис (запущен в июне 2018 года) который предоставляет управляемые высокодоступные отказоустойчивые мастер-ноды Kubernetes, для развертывания сервисов и под K8s на нодах Kubernetes на базе инстансов EC2. \n- Посмотрите раздел [Контейнера и AWS](#контейнера-и-aws) для получения дополнительной информации о контейнерах.\n- EKS - это решение AWS для нативного размещения Kubernetes на AWS. Это не замена ECS, а в ответ на большое доминирование на рынке Kubernetes.\n- EKS не запускает ноды EC2 и должен быть установлен и настроен либо вручную, либо через Cloudformation (или другим решением для автоматизации)\n- Управление EKS осуществляется через утилиту kubectl и конфигурационными файлами Kube. Эти файлы должны быть настроены так, чтобы соединяться с мастером K8s с URL и сертификатом. AWS CLI может автоматически сгенерировать конфигурационный файл, который требуется kubectl для связи с кластером.<sup>[1](#user-content-eks-aws-cli-create-kubeconfig)</sup>\n- Аутенфикация EKS интегрирована с ролями/разрешениями IAM. AWS CLI содержит интегрированную под-комманду для генерации токенов аутенфикации. <sup>[2](#user-content-eks-aws-cli-get-token)</sup> Раньше это делалось с использользованием специального плагина для kubectl называемого [aws-iam-authenticator](https://github.com/kubernetes-sigs/aws-iam-authenticator) (ранее heptio-authenticator-aws).\n- EKS предоставляет [Calico](https://docs.aws.amazon.com/eks/latest/userguide/calico.html) от Tigera для защиты рабочих нагрузок в кластере используя сетевые политики Kubernetes.\n\n### Советы по EKS\n- Множество кластеров поддержиивается при использвовании разных файлов kubeconfig.\n- У AWS есть [руководство по быстрому старту Kubernetes ](https://aws.amazon.com/quickstart/architecture/heptio-kubernetes/) разработанное совместно с Heptio.\n\n### Альтернативы EKS и привязки\n- [ECS](#ecs): это нативная платформа оркестрации контейнеров в Amazon, выпущенная в 2014 году.  Если вы не используете контейнеры на сегодняшний день и хотите начать, ECS - отличный продукт.\n-\t[Kubernetes](https://kubernetes.io): Обширная контейнерная платформа. Доступна как сервис на [Google Cloud](https://cloud.google.com/container-engine/), [AWS](https://aws.amazon.com/eks/), [Digital Ocean](https://www.digitalocean.com/products/kubernetes/) и [Azure](https://azure.microsoft.com/en-us/services/kubernetes-service/).\n-\t[Nomad](https://www.nomadproject.io/): Оркестратор/Планировщик, тесно связанный со стэком Hashicorp (Consul, Vault и т.д.).\n\n### Ошибки и ограничения, связанные с EKS\n- Конфигурации подов и сервисов могут быстро потреблять IP адреса внутри VPC. Надлежащий уход и обслуживание должны применяться, чтобы избежать истощения IP пространства.\n- На текущий момент не существует интегрированного мониторинга в CloudWatch для под или сервисов EKS, таким образом вам необходимо развернуть мониторинговую систему, которая поддерживает Kubernetes, такую как Prometheus.\n- Автоматическое масштабирование на основе CPU/памяти ноды ограничено, так как вы не будете знать о ожидающих сервисах/подах, которые не могут запуститься. Использование [cluster-autoscaler](https://github.com/kubernetes/autoscaler/tree/master/cluster-autoscaler) может быть полезным для масштабирования на основе использования ресурсов ноды и незапланированных под.\n- [Prometheus](https://prometheus.io/) - это очень популярное мониторинговое решения для K8s, метрики и тревоги можно использовать для отсылки событий в Lambda, SQS или другое решения для действий по автоматическому масштабированию.\n\n### Примечания\n<a name=\"user-content-eks-aws-cli-create-kubeconfig\">**1**</a>: https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html<br />\n<a name=\"user-content-eks-aws-cli-get-token\">**2**</a>: https://aws.amazon.com/about-aws/whats-new/2019/05/amazon-eks-simplifies-kubernetes-cluster-authentication/<br />\n\nFargate\n-------\n\n### Основы Fargate\n-\t📒 [Домашняя страница](https://aws.amazon.com/fargate/) ∙ [ЧаВо](https://aws.amazon.com/fargate/faqs/) ∙ [Расценки](https://aws.amazon.com/fargate/pricing/)\n-   **Fargate** позволяет вам управлять и разворачивать контйнера не задумываясь о запуске подлежащей вычислительной платформе\n-   Fargate выступает в роли нового бэкенда (в дополнению к старом бэкенду на EC2) на котором можно запускать задачи ECS и EKS\n-   Fargate и EC2 в данном контексте называются \"Типы запуска(Launch Types)\"\n-   Fargate позволяет вам рассматривать контейнера, как фундаментальные строительные блоки вашей инфраструктуры.\n\n### Советы по Fargate\n-   Fargate следует подобному образу мышления, как у Lambda, который позволяет вам сосредоточиться на приложениях, вместо работы с низлежащей инфраструктурой\n-   Fargate поддерживается CloudFormation, aws-cli и ecs-cli\n-   Задачи Fargate можно запускать совместно с любыми задачами, использующими тип запуска EC2\n-   💸Перед созданием большого развертывания на Fargate, обязательно оцените затраты и сравните их с альтернативным решением, использующим традиционное развертывание на EC2. Цены на Fargate могут в несколько раз превышать цены на инстансы EC2 эквивалентного размера. Для оценки возможных затрат на оба этих решения, ознакомьтесь с разценками на [EC2](https://aws.amazon.com/ec2/pricing/) и [Fargate](https://aws.amazon.com/fargate/pricing/).\n\n### Альтернативы Fargate и привязки\n-   🚪[Azure Container Instances](https://azure.microsoft.com/en-us/services/container-instances/): Доступно в Microsoft Azure в предварительной версии, позволяет запускать приложения в контейнерах без управления виртуальными машинами\n\n### Ошибки и ограничения, связанные с Fargate\n-   По состоянию на апрель 2018 года, Fargate доступен в [нескольких регионах](https://aws.amazon.com/about-aws/whats-new/2018/04/aws-fargate-now-available-in-ohio--oregon--and-ireland-regions/): us-east-1, us-east-2, us-west-2, and eu-west-1\n-   По состоянию на явнварь 2019 год, Fargate может быть использован с ECS. Поддержка EKS [была изначально запланирована на 2018 год](https://aws.amazon.com/blogs/aws/aws-fargate/), но пока не запущена.\n-   Минимальные ресурсы, которые можно использовать для выполнения задачи ECS в Fargate - 0.25 vCPU и 0.5 GB памяти\n-   [Хранилище задач - эфемерно. Как только задача Fargate останавливается - хранилище удаляется.](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/fargate-task-storage.html)\n\n\nLambda\n------\n\n### Основы Lambda\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/lambda/) ∙ [Руководство пользователя](http://docs.aws.amazon.com/lambda/latest/dg/) ∙ [ЧаВо](https://aws.amazon.com/lambda/faqs/) ∙ [Расценки](https://aws.amazon.com/lambda/pricing/)\n-\t**Lambda** предсталвяет собой предложение бессерверных вычислений в AWS, позволяющее пользователям определять функции Lambda в различных средах выполнения, которые могут быть вызваны с помощью различных триггеров, включая уведомления SNS и вызовы API Gateway. Lambda - ключевой сервис в ['бессерверной' архитектуре AWS](https://aws.amazon.com/lambda/serverless-architectures-learn-more/), вместе с AWS API Gateway, AWS Batch и AWS DynamoDB.\n\n### Советы по Lambda\n\n-\tИдея лежащая в основе 'бессерверной' концепции , что пользователи не управляют развертыванием, масштабированием или обслуживанием физических машин, на которых размещен код их приложения. С Lambda, машина, которая фактически выполняет пользовательскую функцию, абстрагируется как ['контейнер'](http://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html). При определении функции Lambda пользователи могут объявлять объем памяти, доступный для функции, что напрямую влияет на спецификацию физического оборудования контейнера Lambda.\n-\tИзменение объема памяти доступного вашей Lambda функции также затронит объем [CPU](https://aws.amazon.com/lambda/faqs/) доступный ей. \n-\tХотя AWS не предоставляет жестких гарантий относительно повторного использования контейнера, в целом можно ожидать, что неизмененная Lambda функция будет повторно использовать «теплый» (ранее использовавшийся) контейнер, если вызывается вскоре после другого вызова. Пользователи могут использовать это как способ оптимизации своих функций путем интеллектуального кэширования данных приложения при инициализации.\n-\tLambda функция, которая не вызывалась некоторое время, может не иметь теплых контейнеров. В этом случае Lambda должна будет загрузить и инициализировать Lambda-код в сценарии «холодного запуска», что может добавить значительную задержку к вызовам Lambda-функций. Однако производительность «холодного запуска» Lambda [значительно выросла за период 2018-2019 годов](https://levelup.gitconnected.com/aws-lambda-cold-start-language-comparisons-2019-edition-%EF%B8%8F-1946d32a0244) и сейчас занимает в среднем 200-500 мс для простой функции, в зависимости от окружения и конкретного языка.\n-\tLambda функции, запускаемые внутри VPC также [недавно получили определенные улучшения](https://aws.amazon.com/blogs/compute/announcing-improved-vpc-networking-for-aws-lambda-functions/) в скорости холодного запуска.  Ранее холодный запуск этих функций, находящихся внутри VPC, мог занимать ~15 секунд; на текущий момент холодный запуск тех же функций занимает < 1 секунды.  \n-\tСуществует несколько стратегий, позволяющих избежать или смягчить «холодный» запуск. [Гарантированно предоставленный параллелизм(Provisioned concurrency)](https://aws.amazon.com/blogs/aws/new-provisioned-concurrency-for-lambda-functions/) был анонсирован на re:invent 2019 и является эффективным средством для исключения холодного запуска. Другие варианты включают поддержку контейнеров в тепле путем периодического вызова функций, а также предпочтение облегченным средам выполнения, таким как Node.Js, а не Java.\n-\tLambda интегрирована с AWS CloudWatch и во время работы отправляет логи и события в CloudWatc.\n-\tLambda предлагает готовую поддержку AWS X-Ray из коробки. X-Ray может помочь пользователям диагностировать проблемы при выполнении Lambda-функций, предлагая углубленный анализ потока выполнения их Lambda-кода. Это особенно полезно при разборе проблем, вызываемых другими сервисами AWS, так как X-Ray дает вам подробный и простой для анализа [график вызовов](http://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html#lambda-service-map).\n-\tИспользуя [временные события CloudWatch](http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html#CronExpressions), пользователи могут использовать Lambda чтобы периодически запускать задачи, как в cron.\n-\tСобытия, отправленные в Lambda, которые не обрабатываются, могут управляться с помощью [Dead Letter Queue (DLQ) в SQS.](http://docs.aws.amazon.com/lambda/latest/dg/dlq.html)\n-\tБольше о бессерверных вычислениях:\n\t-\t[Martin Fowler's thoughts.](http://martinfowler.com/articles/serverless.html)\n\t-\t[AWS Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model), упрощение, построенное на основе CloudFormation, которое может помочь описывать, управлять и развертывать бессерверные приложения с использованием Lambda.\n\t-\t[Serverless](https://github.com/serverless/serverless) - один из наиболее популярных фреймворков для создания бессерверных приложений используя AWS Lambda или другой вариант бессерверных вычислений and other serverless compute options.\n\t-\t[Другие полезные фреймворки.](https://github.com/anaibol/awesome-serverless#frameworks)\n\n### Альтернативы Lambda и привязки\n\n-\t🚪Другие облачные провайдеры также предоставляют подобные сервисы под разными именами, включая [Google Cloud Functions](https://cloud.google.com/functions/), [Azure Functions](https://azure.microsoft.com/en-us/services/functions/), и [IBM OpenWhisk](http://www.ibm.com/cloud-computing/bluemix/openwhisk/). Также, если вы используете Kubernetes, другой альтернативой Lambda является [OpenFaaS] (https://github.com/openfaas/faas)\n\n### Ошибки и ограничения, связанные с Lambda\n\n- 🔸Тестирование Lambda-функций, как локально, так и удаленно, может быть сложным. Для облегчения этой задачи доступно несколько инструментов, включая официально поддерживаемый [SAM Local](https://github.com/awslabs/aws-sam-local).\n- 🔸Управление большим количеством функций Lambda - это сложный рабочий процесс, а инструменты для управления развертываниями Lambda все еще не совершенны.\n- 🔸Официальный рабочий процесс AWS относительно управления функцией [версионности и псевднонимов](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html) полон боли. Один из вариантов - избежать создания версий Lambda, абстрагируя рабочий процесс развертывания от Lambda. Одним из способов достижения этого является развертывание приложения на последовательных этапах, с отдельной учетной записью AWS для каждого этапа, где каждая учетная запись должна знать только о последней версии, а откаты и обновления обрабатываются с помощью внешних инструментов.\n- 🔸По состоянию на октябрь 2017 год, минимальная плата взымается за вызов Lambda за 100 миллисекунд, так что уменьшение срока запуска ниже этого времени ни принесет никаких преимуществ.\n- 🔸При добавлении/удалении S3 бакетов в качестве триггеров для Lambda-функции может возникнуть эта ошибка: \"There was an error creating the trigger: Configuration is ambiguously defined. Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type.\" В этом случае вы можете вручную удалить событие Lambda на вкладке \"Events\" в разделе \"Properties\" S3 бакета.\n- 🔸Управление размером артефактов развертывания может быть проблемой, особенно при использовании Java. Вариантом смягчения этой проблемы является включение [proguard](https://www.guardsquare.com/en/proguard) и загрузка зависимостей в среду выполнения в /tmp.\n- Когда вы используете DynamoDB, как триггер для вашей Lambda-функции, может возникнуть следующая ошибка: \"PROBLEM: internal Lambda error. Please contact Lambda customer support.\" Обычно это просто означает, что Lambda не может обнаружить что-либо в потоке DynamoDB за последние 48 часов. Если проблема не устранена, удаление и повторное создание триггера может помочь.\n- 🔸Если вашей Lambda-функции нужен доступ к ресурсам в VPC (например, ElastiCache или RDS), ее необходимо будет развернуть в нем. Это повышает время холодного старта, так как Эластичный сетевой интерфейс(Elastic Network Interface (ENI)) должен быть зарегистрирован в VPC для каждой конкурентной функции. AWS также имеет относительно низкий начальный предел (350) для числа ENI, которые могут быть созданы в VPC, однако его можно увеличить до 1000, если для поддержки AWS будет подготовлено хорошее обоснование.\n-\t🔸 Lambda также имеет несколько [**ресурсных ограничений(resource limits)**](http://docs.aws.amazon.com/lambda/latest/dg/limits.html) по состоянию на июнь 2017 года:\n\t-\t**6MB** - размер полезной нагрузки запроса или ответа.\n\t-\t**50 MB** - ограничение на размер сжатого .zip/.jar файла пакета развертывания.\n\t-\t**250 MB** - ограничение на размер кода/зависимостей в пакете до сжатия.\n\t- **500 MB** - ограничение локального хранилища в /tmp.\n\n### Примеры Lambda-кода\n\n-\t[Fan-out](https://github.com/awslabs/aws-lambda-fanout) Пример использования Lambda для “разветвления” или копирования данных из одной службы, в данном случае Kinesis, в несколько других служб данных AWS. Направлениями для разветвления данных в этом примере включают  IoT, SQS и прочие.\n-\tЭтот [AWS limit monitor using Lambdas](https://github.com/awslabs/aws-limit-monitor) показывает использование нескольких Lambda-функций для мониторинга.\n-\tЭтот [Lambda ECS Worker Pattern](https://github.com/awslabs/lambda-ecs-worker-pattern) показывает использования  Lambda в рабочем процессе, где данные берутся из S3 Lambda-функцией, отправляются в очередь, а затем передаются в ECS для дальнейшей обработки.\n-\t[Secure Pet Store](https://github.com/awslabs/api-gateway-secure-pet-store) простое приложение на Java, которое использует Lambda и API Gateway с Cognito (для аутентификации пользователей).\n-\t[aws-lambda-list](https://github.com/unixorn/aws-lambda-list) - список \"надеюсь полезных AWS Lambda-функций и ресурсов о Lambda\". Довольно таки много примеров кода; как обычно, никто не гарантирует, что код тестирован. Будьте бдительны.\n\n🚧 [*Пожалуйста помогите дополнить этот неполный раздел.*](CONTRIBUTING.md)\n\nAPI Gateway\n-----------\n\n### Основы API Gateway\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/api-gateway/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/apigateway/latest/developerguide/) ∙ [ЧаВо](https://aws.amazon.com/api-gateway/faqs/) ∙ [Расценки](https://aws.amazon.com/api-gateway/pricing/)\n-\t**API Gateway** предоставляет масштабируемый, защищенный интерфейс для сервисных API, и может работать с Lambda, Elastic Beanstalk, или обычными EC2 сервисами.\n-\tПозволяет развертывать “serverless” приложения созданные в Lambda.\n-\t🔸Переключение между развертываниями после обновлений может быть сложным. Отстутвуют встроенные механизмы по переносу одного доменного имени с одного API Gateway на другой. Поэтому может потребоваться создать дополнительный промежуточный слой (даже другой API-Gateway), чтобы обеспечить плавный переход от одного развертывания к другому.\n\n### Альтернативы API Gateway и привязки\n\n- [Kong](https://getkong.org) это локальный шлюз API и микросервисов с открытым исходным кодом на nginx с Lua. Kong расширяем с помощью “плагинов”.\n- [Tyk](https://tyk.io) это шлюз API написанный на год Go и доступен в облачных, частных или гибридных средах.\n\n### Советы по API Gateway\n\n-\t🔹До ноября 2011 года, вы могли посылать и принимать данные только открытым текстом(таким образом бинарные данные  было необхоидмо кодировать в base64), но бинарные данные [теперь](https://aws.amazon.com/about-aws/whats-new/2016/11/binary-data-now-supported-by-api-gateway/) поддерживаются.\n-\tAPI Gateway поддерживает спецификацию OpenApi (также известную, как [Swagger](https://swagger.io/)). Это позволяет вам описывать ваш API без учета языка и использовать различные инструменты для генерации кода, поддерживающего ваш API.\n-\tСоздание клиентов чрезвычайно просто - либо через консоль AWS, либо с помощью API get-sdk.\n-\tAPI Gateway интегрируется с CloudWatch из-коробки, позволяя легко логировать запросы и ответы.\n\t-\tОбратите внимание, что если ваш запрос или ответ слишком велики, CloudWatch будет обрезать лог. Для полного логирования запросов/ответов, убедитесь что вы это сделали в ваших интеграциях (например Lambda).\n\t-\tХорошей практикой при вызове API-интерфейсов API Gateway является регистрация идентификатора запроса на клиенте. Позже вы сможете сослаться на эти идентификаторы запросов в CloudWatch для упрощения отслеживания и отладки.\n-\tЕсть множество способов обезопасить свои API, включая встроенную поддержку [AWS Cognito](http://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html). Для большинства случаев применения, Cognito самый простейший путь аутенфицировать пользователей.\n\t-\tХотя вы можете использовать собственное решения используя [собственную службу авторизации](http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html), обычно в этой роли выступает Lambda, где вы определяете может ли быть принят запрос или нет.\n-\tХотя API Gateway хорошо подходит для разработки в стиле REST, вполне разумно также реализовать API-интерфейс в стиле RPC в API Gateway. В зависимости от случаев применения, это может привести к значительному упрощению структуры API и к более плавной работе  клиентов. \n\t-\tAPI в стиле RPC особенно полезны при разработке сервисов, которые находятся глубже в стеке и не предоставляют контент непосредственно пользователям.\n\n\n### Ошибки и ограничения, связанные с API Gateway\n\n-\t🔸API Gateway поддерживает только шифрованные (https) входные точки, и не поддерживает незашифрованный HTTP. (Это возможно хорошая штука.)\n-\t🔸API Gateway не поддерживает мульти-регионное развертывание для высокой доступности. Это сервис, который разворачивается в одном регионе, но поставляется с глобальной точкой входа, которыа обслуживаются AWS edge locations (как и CloudFront distribution). Вы не можете иметь несколько API Gateway с одним именем хоста в разных регионах AWS и использовать Route 53 для распределения траффика. Больше информации [в этом сообщении на форуме](https://forums.aws.amazon.com/thread.jspa?messageID=735342&#735342).\n- 🔸Таймаут интеграции: Любые способы интеграции (например Lambda, HTTP) в API Gateway имеют таймауты, как описано [здесь](http://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#api-gateway-limits). В отличии от некоторых лимитов, эти таймауты не могут быть увеличены. \n- 🔸API Gateway возвращает статус код 504 в случае любой сетевой или низкоуровневой транспортной проблемы. Когда это происходит, вы можете увидеть сообщение в логах CloudWatch для данного запроса, которое включает в себя сообщение: `Execution failed due to an internal error`. Одной из возможных причин этой ошибки является то, что, несмотря на то, что ваш внутренний(бэкенд) сервер работает и работает, он может делать что-то за пределами спецификации HTTP (например, не отправлять правильно сформированные фрагментированные сообщения). Вы можете протестировать это, ткнувшись в ваш внутренний сервер(бэкенд) напрямую, командой `curl --raw -S -i <backend-endpoint-url>` и посмотреть, на что он ругается.\n-\t🔸Поддержка AWS X-Ray существует, но неудобна в использовании. Если у вас есть другие сервисы AWS, вызывающие API Gateway, ваша трассировка на этом, похоже, закончится. API Gateway также не будет виден, как нода в карте сервисов. [Больше информации тут](http://docs.aws.amazon.com/xray/latest/devguide/xray-services-apigateway.html).\n-\t🔸Будьте осторожны, используя функцию экспорта. Получившийся в результате шаблон Swagger часто не полный и не интегрируется нормально с расширениями Swagger для таких вещей, как CORS.\n-\t🔸Многие изменения в ресурсах API Gateway необходимо 'развернуть' с помощью консоли или вызова API. К сожалению, API Gateway ужасен в оповещении пользователя, когда изменения размещаются для развертывания и какие изменения требуют развертывания. Если вы что-то изменили в своем API, а изменения не вступили в силу, есть вариант, что вам просто нужно его развернуть.\n\t-\tВ частности, когда разворачиваешь API Gateway как часть стэка CloudFormation, изменения автоматически не развернутся, пока разворачиваемый ресурс сам не будет изменен. Вы можете обойти эту проблему, всегда меняя ресурс развертывания в обновлении CloudFormation или запуская пользовательский ресурс, обеспечивающий подтверждение развертывание.\n\t-\tВ качестве альтернативы, используя определение [модели Serverless приложений](https://github.com/awslabs/serverless-application-model) для ресурсов API Gateway, вы всегда можете быть уверены, что API развернется во время обновления стэка, так как SAM будет генерировать новое развертывание каждый раз. \n- 🔸API Gateway не поддерживает вложенные параметры запроса для запросов метода.\n- 🔸API Gateway ограничивает количество ресурсов 3 сотнями, как описано [здесь](http://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#api-gateway-limits). Это следует учитывать, когда вы начинаете использовать API Gateway как платформу, на которой ваша команда / организация развертывает на этом же API Gateway.\n\n🚧 [*Пожалуйста помогите дополнить этот неполный раздел*](CONTRIBUTING.md)\n\nStep Functions\n------\n\n### Основы Step Functions\n-\t📒 [Домашняя страница](https://aws.amazon.com/step-functions/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) ∙ [ЧаВо](https://aws.amazon.com/step-functions/faqs/) ∙ [Расценки](https://aws.amazon.com/step-functions/pricing/)\n-\t**Step Functions** - это способ AWS по созданию конечных автоматов, которые управляют бессерверным рабочим процессом.\n\n### Советы по Step Function\n-   Многообразие структур поддерживается, включая ветвление, параллельные операции и ожидание.\n-   [Задачи(Tasks)](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-tasks.html) представляют из себя реальные рабочие узлы и часто, лямбда функции, но также могут быть еще и [Активности(Activities)](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-activities.html) которые являются внешне управляемыми задачами, реализованными так, как вам угодно.\n-   У конечных автоматов есть [данные](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-state-machine-data.html), которые \"обрабатываются\" пошагово и могут быть изменены или добавлены, по мере запусков конечного автомата.\n-   Лучше всего, если ваши задачи являются идемпотентными, отчасти потому, что вы можете повторно запустить конечный автомат с теми же входными данными во время отладки\n-   Консоль AWS облегчает изучение состояния выполнения на различных этапах.\n    -   Консоль позволяет сделать это за несколько шагов:\n        -   выберите вкладку \"input\" на неудачно запущенном задании\n        -   скопируйте входные данные (JSON)\n        -   выберите имя конечного автомата в \"хлебных крошках\"(навигационной цепочке сверху)\n        -   запустите новое выполнение, вставив входные данные, которые вы скопировали ранее\n\n### Ошибки и ограничения, связанные с Step Functions\n-   Step Functions на уровне бесплатного использования позволяет производить 4000 переходов в месяц бесплатно. Впоследствии, оплата составляет $0.025 за тысячу переходов.\n-   Вы можете производить множество одновременных запусков, однако помните о лимитах троттлинга lambda. Раньше эти ограничения был на учетную запись, на регион, но недавно их стало возможным устанавливать на уровне lambda функций.\n-   Запуски Step Function ограничены 25,000 событий. Каждый шаг создает несколько событий. Это означает, что [цикл с использованием Lambda](https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-create-iterate-pattern-section.html) ограничен количеством итераций равным 3000, после чего продолжение возможно [путем нового запуска](https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-continue-new.html).\n\nRoute 53\n--------\n\n### Основы Route 53\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/route53/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/) ∙ [ЧаВо](https://aws.amazon.com/route53/faqs/) ∙ [Расценки](https://aws.amazon.com/route53/pricing/)\n-\t**Route 53** - это DNS сервис AWS.\n\n### Альтернативы Route 53 и привязки\n\n-\tИсторически, AWS не спешил проникать на рынок DNS (поскольку это часто обусловлено предполагаемой надежностью и долгосрочными отношениями с поставщиками), но Route53 дошел до зрелой стадии и [становится стандартным вариантом](https://www.datanyze.com/market-share/dns/) для многих компаний. Route 53 дешев, согласно историческим стандартам DNS, так как он имеет большую глобальную сеть, с географическим DNS и другими ранее считавшимися “премиальными” функциями. Это удобно, если вы уже используете AWS.\n-\t⛓Как правило, вы не привязаны к провайдеру DNS для простых случаев использования, но все чаще становитесь связанными, когда используете определенные функции такие, как географическая маршрутизация или записи Route 53 alias.\n-\t🚪Существует множество альтернативных провайдеров DNS, начиная от давних премиальных брендов, таких как [UltraDNS](https://www.neustar.biz/services/dns-services) и [Dyn](http://dyn.com/managed-dns/) до менее известных, более скромных брендов, таким как [DNSMadeEasy](http://www.dnsmadeeasy.com/). Большинство экспертов DNS скажут вам, что рынок достаточно непрозрачен, что надежность и производительность не очень хорошо соотносятся с ценой.\n-\t⏱Route 53 обычно находится посредине в тестах производительности, например [отчеты SolveDNS](http://www.solvedns.com/dns-comparison/).\n\n### Советы по Route 53\n\n-\t🔹Знайте о записи Route 53 “alias”:\n\t-\tRoute 53 поддерживает все стандартные типы запросов DNS, но также имейте ввиду, что [**наборы записей псевдонимов ресурсов**](http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-choosing-alias-non-alias.html) не являются стандартной частью DNS, а является специфичной функцией Route 53. (Она доступна и у других провайдеров DNS, но каждый провайдер предлагает ее под своим именем.)\n\t-\tПсевдонимы(Alias) - это что-то вроде внутренних имен (немного похоже CNAME), которые резолвятся внутри на серверной стороне. Например,традиционно вы могли использовать CNAME для указание на DNS имя CLB или ALB, но гораздо лучше сделать псевдоним на тот же балансировщик нагрузки.  Эффект тот же, но в последнем случае внешне все, что видит клиент - это цель, на которую указывает запись.\n\t-\tЧасто целесообразно использовать псевдонимы в качестве альтернативы CNAME, поскольку их можно мгновенно обновить с помощью вызова API, не беспокоясь о распространении DNS.\n\t-\tВы можете использовать их с  CLB/ALB или любым другим ресурсом AWS, который их поддерживает. \n\t-\tЧто смущает, это то, что у вас могут быть псевдонимы типов CNAME и A, в зависимости от типа цели, на которую указывает запись.\n\t-\tПоскольку псевдонимы являются расширениями для обычных записей DNS, при экспорте вывод [файл зоны](https://en.wikipedia.org/wiki/Zone_file) будет включать дополнительные строки с нестандартными записями “ALIAS”.\n-\t[**Маршрутизация на основе времени задержки(Latency-based routing)**](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html#routing-policy-latency) позволяет пользователям по всему земному шару автоматически направляться в ближайший регион AWS, в котором вы работаете, таким образом время задержки уменьшается.\n-\tПоймите, что регистрация домена и управление DNS(размещение зон) - это две отдельные услуги Route 53. Когда вы покупаете/переносите домен, Route 53 автоматически назначает ему четыре сервера имен (например, ns-2.awsdns-00.com). Route 53 также предлагает автоматически создать зону для управления DNS, но вы не обязаны управлять зоной DNS в том же аккаунте или вообще в Route 53; вам просто нужно создать запись NS в Route 53, указывающую на серверы, назначенные вашему домену.\n  - Один из вариантов использования - провести регистрацию домена (очень критичного) в [бастионном аккаунте(bastion account)](https://cloudonaut.io/your-single-aws-account-is-a-serious-risk/), а управлять зоной в другом аккаунте, который доступен для ваших приложений.\n\n### Ошибки и ограничения, связанные с Route 53\n-   🔸Приватные зоны отвечают только на DNS запросы, которые исходят из VPC. В результате, Route 53 не будет отвечать на запросы сделанные через VPN или Direct connect. Чтобы это обойти вам необходимо реализовать [решение DNS в гибридном облаке](https://d1.awsstatic.com/whitepapers/hybrid-cloud-dns-options-for-vpc.pdf) или использовать IP адреса выданные Simple AD для запросов к внутренней зоне.\n\n\nCloudFormation\n--------------\n\n### Основы CloudFormation\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/cloudformation/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/) ∙ [ЧаВо](https://aws.amazon.com/cloudformation/faqs/) ∙ [Расценки](https://aws.amazon.com/cloudformation/pricing/), использование Cloudformation дополнительно не оплачивается.\n-\t**CloudFormation** позволяет вам управлять наборами ресурсов из сервисов AWS сгруппированными, в **[стэки(stacks)](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html#d0e3917)**. CloudFormation позволяет вам описывать эти стэки файлами шаблонов используя [JSON](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#aws-properties-ec2-instance-syntax.json) или [YAML](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#aws-properties-ec2-instance-syntax.yaml). CloudFormation вляется одним из основных сервисов, лежащих в основе применяемых в AWS [принципов инфраструктура, как код](https://d0.awsstatic.com/whitepapers/DevOps/infrastructure-as-code.pdf) и является критичной, в целях обеспечения повторяющихся и целостных развертываний инфраструктуры.\n-\t💸CloudFormation сам по себе [дополнительно не оплачивается](https://aws.amazon.com/cloudformation/pricing/); вы платите только за использованные ресурсы.\n\n### Альтернативы CloudFormation и привязки\n\n-\tHashicorp’s [Terraform](https://www.terraform.io/intro/vs/cloudformation.html) - это сторонняя альтернатива, которая птакже может поддерживать другие облачные платформы/провайдеров, включая [Azure](https://www.terraform.io/docs/providers/azure/) и [OpenStack](https://www.terraform.io/docs/providers/openstack/).\n- 🔸Некоторые функции AWS могут быть недоступны в Terraform (например, ElastiCache с несколькими AZ с использованием Redis), и вам, возможно, придется прибегнуть к встроенным шаблонам CloudFormation.\n-\t[Pulumi](https://www.pulumi.com/) позволяет командам определять и создавать собственную облачную инфраструктуру, как код в любом облаке на любом языке. От контейнеров до serverless, от Kubernetes до инфраструктуры.\n\n### Советы по CloudFormation\n\n-\tПроверяйте ваш стэк в другом аккаунте AWS. CloudFormation действительно хорош, когда необходимо произвести множество развертываний одного стэка в различных регионах и аккаунтах AWS. Обычной практикой является последовательное развертывание стэков, и в результат успешного окончания всех стадий - перевод в боевую(продуктивную) среду. \n-\tИзбегайте ситуаций, когда синтаксические ошибки будут поедать ваше время во время развертывания, путем запуска `validate-template`.\n-\tCloudFormation иногда медленно обновляется, и некоторые новые сервисы(а также новые возможности  старых сервисов) не сразу же можно описать в шаблоне. Если вам необходимо развернуть ресурс или функцию, которая пока не поддерживается шаблоном, CloudFormation позволяет запускать произвольный код(используя [Lambda](#lambda)) во время создания или обновления стэка через [собственные ресурсы(custom resources)](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html).\n-\tСобственные ресурсы превращают CloudFormation в, по-настоящему, мощный инструмент,поскольку вы можете довольно легко выполнять всевозможные полезные действия, такие как тесты работоспособности, первоначальная настройка таблиц Dynamo или S3, очистка старых журналов CloudWatch и т. д.\n\t- Для написания собственных ресурсов на Javascript, AWS предоставляет хороший справочник в [документации.](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-custom-resources-lambda-lookup-amiids.html)\n-\tCloudFormation предлагает визуальный [дизайнер шаблонов](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/working-with-templates-cfn-designer-walkthrough-createbasicwebserver.html) который может быть очень полезен, пока вы осваиваетесь с синтаксисом шаблона.\n-\tПосредством использования [StackSets](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-concepts.html), пользователи могут описать и развернуть целостное продуктовое приложение, состоящее из множества стэков (один сервис на стэк) в одном шаблоне CloudFormation.\n-\tЕсли вы разрабатываете serverless приложение(например, используя Lambda, API Gateway) CloudFormation предлагает упрощенный формат шаблона, называемый [SAM](https://github.com/awslabs/serverless-application-model).\n-\t❗Используйте ограничивающую [политику стэка(stack policy)](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html)! Без нее вы можете случайно удалить живые производственные ресурсы, что может привести к длительному простою. \n-\t❗Включите [защиту от отключения(termination protection)](https://aws.amazon.com/about-aws/whats-new/2017/09/aws-cloudformation-provides-stack-termination-protection/) на всех ваших стэках, чтобы избежать дорогостоящих инцидентов!\n-\t[Справочник по шаблонам](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-reference.html) CloudFormation - незаменим, когда разбираешься, что возможно, а что нет в CloudFormation.\n-\t[Troposphere](https://github.com/cloudtools/troposphere) - Библиотека для языка Python, которая облегчает создание шаблонов CloudFormation.\n\t- На текущий момент поддерживаются типы ресурсов [AWS](https://github.com/cloudtools/troposphere#currently-supported-aws-resource-types) и [OpenStack](https://github.com/cloudtools/troposphere#currently-supported-openstack-resource-types).\n\t- Troposphere пытается поддерживать все ресурсы, которые можно описать в шаблонах CloudFormation. \n\t- Встроена проверка на [ошибки](https://github.com/cloudtools/troposphere#examples-of-the-error-checking-full-tracebacks-removed-for-clarity).\n\t- [awacs](https://github.com/cloudtools/awacs) является рекомендуемым дополнением, которое позволяет генерировать политику доступа AWS в формате JSON путем написания кода на Python.\n-\t[stacker](http://stacker.readthedocs.io/en/latest/) - приложение, написанное на Python, которое облегчает описание, конфигурацию, оркестрацию и управление зависимостями в стэках CloudFormation средах описываемых множеством пользователей.\n-\tЕсли вы создаете различные стэки с одинаковыми слоями, будет полезным создать отдельные шаблоны для различных слоев, которые вы потом можете использовать путем использования [AWS::CloudFormation::Stack](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html).\n-\t🔸Избегайте жесткого определения параметров ресурса, которые могут измениться. Максимально используйте параметры стека и используйте значения параметров по умолчанию.\n-\t🔹До [2016 года](https://aws.amazon.com/about-aws/whats-new/2016/09/aws-cloudformation-introduces-yaml-template-support-and-cross-stack-references/), CloudFormation использовал только неудобный формат JSON, который затруднял как чтение, так и отладку. Чтобы эффективно с ним работать, обычно привлекались дополнительные инструменты, включая конвертацию в YAML, но теперь [YAML поддерживается напрямую](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-formats.html).\n- По возможности экспортируйте соответствующие [физические идентификаторы](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) из ваших стэков путем описания [выходных данных(Outputs) в вашем шаблоне CloudFormation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html). Это имена назначенные созданным ресурсам. Выходные данные могут быть получены от вызова API `DescribeStack`, и быть импортированы в другие стэки, как часть [недавно добавленных](https://aws.amazon.com/about-aws/whats-new/2016/09/aws-cloudformation-introduces-yaml-template-support-and-cross-stack-references/) [кросс-стековых ссылок](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-crossstackref.html).\n\t-Обратите внимание, что импорт выходных данных из одного стэка в другой, создает жесткую зависимость, отслеживаемую CloudFormation. Вы не сможете удалить стэк, поставляющий выходные данные, пока не будут удалены стэки, использующие эти данные в качестве входных. \n-\tCloudFormation может быть настроен для [отсылки оповещений через SNS](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-add-tags.html) относительно изменений состоянияЮ включая программную поддержку ситуаций, когда сборка стэка заканчивается неудачно, простое почтовое сообщение с оповещением будет отправлено, чтобы соответствующие люди были проинформированы.\n-\tCloudFormation позволяет использовать[**условия**](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) во время создания стэка.\n\t-\tОдин из распространенных способов использования этой возможности - поддержка шаблонов CloudFormation для нескольких сред - путем их настройки для использования операторов if-else со значением [переданного параметра] (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) (например,  “env”), специфичные для среды значения для таких вещей, как идентификаторы VPC, идентификаторы SecurityGroup и имена AMI, можно передавать в повторно используемые универсальные шаблоны.\n-\t**Храните ваши шаблоны CloudFormation в системе контроля версий!** В облаке приложение - это комбинация написанного кода и инфраструктуры, в которой оно работает. Путем хранения **и того и того** в системе контроля версий, всегда легко откатиться на рабочее состояние.\n-\tИзбегайте явного именования ваших ресурсов (например, таблиц в DynamoDB). При развертывании нескольких стеков в одной учетной записи AWS эти имена могут вступать в противоречие, что может замедлить тестирование. Предпочитайте использование ссылок на ресурсы вместо явных имен.\n-\tДля тех вещей, которые не должны быть когда-либо удалены, вы можете выставить явную политику удаления(DeletionPolicy) на ресурсы, это предотвратит удаление ресурсов даже в том случае, если сам CloudFormation стэк удален. Это полезно для любого, кто поддерживает такие ресурсы, где пересоздание может стоить больших трудозатрат, например таблицы DynamoDB, или вещи, которые смотрят в окружающий мир, например API API Gateway.\n\n### Ошибки и ограничения, связанные с CloudFormation\n\n-\t🔸Стек CloudFormation может оказаться в самых разных состояниях. Сообщения об ошибках, как правило, малоинформативны, и часто для получения рабочего шаблона требуется несколько циклов наблюдения-настройки-повторного развертывания. Внутренний конечный автомат для [всех меняющихся состояний](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html) чрезвычайно непрозрачен.\n-\t🔸Некоторые межрегиональные операции невозможны в CloudFormation без использования собственного ресурса, например такие как [межрегиональная подписка SNS](https://github.com/serverless/serverless/issues/3676).\n-\t🔸Хотя использование ресурсов, созданных вручную, совместно с ресурсами, созданными CloudFormation, нецелесообразно, иногда это неизбежно. Если это возможно, переведите ВСЁ управление ресурсами на шаблоны CloudFormation и предоставьте доступ только для чтения в консоль.\n-\t❗Изменения в ресурсах входящих в стэк, сделанные за пределами CloudFormation может потенциально привести к зависанию стэка  в режиме UPDATE\\_ROLLBACK\\_FAILED. Стэки в таком состоянии могут быть восстановлены путем использования [команды continue-update-rollback](https://aws.amazon.com/blogs/devops/continue-rolling-back-an-update-for-aws-cloudformation-stacks-in-the-update_rollback_failed-state/). Эта команда может быть вызвана из консоли или из CLI. Параметр [--resources-to-skip](http://docs.aws.amazon.com/cli/latest/reference/cloudformation/continue-update-rollback.html), использующийся в CLI может быть полезен, если команда continue-update-rollback выполнилась неудачно. Новая функция [Drift Detection](https://aws.amazon.com/blogs/aws/new-cloudformation-drift-detection/) может быть использована для определения внешних изменений в стэке.\n-\t🔸CloudFormation - полезен, но сложен и имеет множество болевых точек. Многие компании находят альтернативные решения, но многие компании используют его, но только со значительными дополнительными инструментами.\n-\t🔸CloudFormation может быть очень медленным, в особенности для таких вещей, как раздачи CloudFront и записи CNAME в Route53.\n-\t🔸Сложно собрать хорошую конфигурацию CloudFormation с текущего состояния. AWS предлагает [определенный трюк, чтобы сделать это](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-using-cloudformer.html), но он очень кривой.\n\t- CloudFormer также не обновлялся годами (по состоянию на октябрь 2017 года), не поддерживает шаблонирование многих новых сервисов, и не полностью описывает даже текущие сервисы, потому что они были обновлены. Как пример, таблицы DynamoDB описанные в CloudFormer не содержат определений TTL или конфигурацию автоматического масштабирования. Существует сторонняя версия этого инструмента с большим количеством поддерживаемых ресурсов, именуемая [Former2](https://github.com/iann0036/former2).\n-\t🔸Многие пользователи вообще не используют CloudFormation из-за его ограничений или из-за того, что считают другие решения более предпочтительными. Часто есть другие способы достижения тех же целей, такие как управляемые вами скрипты (Boto, Bash, Ansible и т.д.), которые создают инфраструктуру, или решения на основе Docker. ([Convox](https://convox.com/)).\n-\t🔸Развертывание больших стэков (например, большого количества ресурсов) может быть проблематичным по причине неинтуитивных лимитов API. Например, в API Gateway `CreateDeployment` API имеет лимит по умолчанию - [3 запроса в минуту](https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html) по состоянию на 1/12/2018. Этот предел легко превышается даже в стеках CloudFormation среднего размера. Создание оповещений CloudWatch другой часто превышаемый лимит (`PutMetricAlarm`, 3 tps по состоянию на 1/12/2018), особенно когда создается много политик масштабирования для DynamoDB. Одним из путей обхода этого лимита является включение условия 'DependsOn' в цепочку создания ресурса в шаблоне CloudFormation.\n-\t🔸Создание/удаление стэков может быть не идеально чистым. Некоторые ресурсы оставляют после себя следы в вашем AWS аккаунте даже после удаления. Например, Lambda оставляется после себя лог группы в CloudWatch, которые никогда не истекают.\n\nVPC, Сетевая безопасность и Группы безопасности\n-------------------------------------------\n\n### Основы VPC\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/vpc/) ∙ [Руководство пользователя](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide) ∙ [ЧаВо](https://aws.amazon.com/vpc/faqs/) ∙ [Группы безопасности](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) ∙ [Расценки](https://aws.amazon.com/vpc/pricing/)\n-\t**VPC** (Виртуальное частное облако(Virtual Private Cloud)) - это виртуализированный сетевой уровень ваших систем AWS.\n-\tБольшая часть пользователей AWS должна иметь базовое понимание концепций VPC, но только некоторым потребуется разбираться во всех деталях. Конфигурации VPC могут быть простейшими или экстремально сложными, в зависимости от степени требований к вашей сети и безопасности.\n-\tВсе современные учетные записи AWS (которые созданы [после 2013-12-04](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html)) являются аккаунтами “EC2-VPC”, которые поддерживают VPC и все инстансы находятся в VPC по умолчанию. Более старые учетные записи могут до сих пор использовать режим “EC2-Classic”. Некоторые функции не работают без VPC, так что вы наверняка захотите [мигрировать](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html).\n\n### Советы по VPC и сетевой безопасности\n\n-\t❗**Группы безопасности(Security Groups)** - первая линия обороны ваших серверов. Экстремально ограничиваейте набор открытых портов для всех входящих соединений. В общем, если вы используете CLB, ALB или любой другой балансировщик траффика, единственные порты, которые должны быть открыты - это порт 22 и любой порт, который использует ваше приложение. Политика доступа в группах безопасности - 'запрет по умолчанию'.\n-\t**Гигиена портов:** Хорошей привычкой является выбор уникальных портов из необычного диапазона для каждого из разных типов продуктивных сервисов. Например, ваш фронтенд веб-сервер может использовать порт 3010, ваши бэкенд сервера - порты 3020 и 3021, а ваш инстанс Postgres обычный порт 5432. Затем убедитесь, что у вас есть детализированные группы безопасности для каждого набора серверов. Это делает вас дисциплинированным в отношении учета ваших сервисов, а также обеспечит дополнительную защиту от ошибок. Например, если у вас случайно есть дополнительный сервер Apache, работающий на порте 80 по умолчанию на внутреннем сервере, он не будет выставлен наружу.\n-\t**Миграция с EC2-Classic**: Для миграции со старых развертываний EC2-Classic в современный EC2-VPC прочтите [эту статью](http://blog.kiip.me/engineering/ec2-to-vpc-executing-a-zero-downtime-migration/), она может помочь.\n\t-\tВы можете [переносить Elastic IP между EC2-Classic и EC2-VPC](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html#using-eip-migration).\n-\tДля основного использования AWS, вполне достаточного одного VPC по умолчанию. Но, по мере расширения, вам стоит рассмотреть более тщательное составление вашей сетевой топологии. Хороший обзор лучших практик - [тут](http://blog.flux7.com/blogs/aws/vpc-best-configuration-practices).\n-\tРассмотрите возможность управления доступом к вашим частным ресурсам AWS через [VPN](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpn-connections.html).\n\t-\tВы получаете прозрачность и контроль подключений и попыток подключения.\n\t-\tВы предоставляете меньшую площадь для атаки по сравнению с раскрытием отдельных (потенциально аутентифицированных) сервисов через общедоступный Интернет.\n\t\t-\tНапример, баг в парсере YAML, который используется на админстративном сайте Ruby on Rais, является гораздо менее серьезной проблемой, если админстративный сайт виден только из внутренней сети и доступен только через VPN.\n\t-\tДругой распространенный шаблон (особенно по мере увеличения масштабов развертывания, ужесточения требований к безопасности или нормативных требований или увеличения размеров группы) - это обеспечение создания [узла бастиона](https://www.pandastrike.com/posts/20141113-bastion-hosts) за VPN, через который должны проходить все соединения SSH.\n\t-\tДля дешевого VPN доступа к частным ресурсам AWS рассмотрите возможность использования программного обеспечения VPN «точка-сайт», такого как [OpenVPN](https://openvpn.net/). Он может быть установлен, как используя [официальный AMI](https://docs.openvpn.net/how-to-tutorialsguides/virtual-platforms/amazon-ec2-appliance-ami-quick-start-guide/), правда на бесплатной лицензии вы ограничены 2 одновременными пользователями, или может быть установлен используя пакет openvpn на Linux. Пакет для Linux допускает неограниченное количество одновременных пользователей, но установка менее проста. Этот [скрипт установки OpenVPN](https://github.com/Nyr/openvpn-install) поможет вам легко провести установку и добавить клиентские ключи.\n-\t🔹Подумайте об использовании других групп безопасности в качестве источников для правил групп безопасности вместо использования CIDR - таким образом, всем узлам в исходной группе безопасности и узлам в этой группе безопасности, и только им разрешен доступ. Это гораздо более динамичный и безопасный способ управления правилами групп безопасности.\n-\t**Поточные логи VPC(VPC Flow Logs)** позволяет вам мониторить сетевой траффик, как входящий, так и исходящий, а также траффик внутри VPC. Логи сохраняются в группах логов CloudWatch и могут использоваться для мониторинга безопасности (с использованием сторонних инструментов), оценки производительности и расследования информационных инцидентов.\n\t-\tОзнакомьтесь [с руководством пользователя по поточным логам VPC(VPC Flow Logs)](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/flow-logs.html) для получения общей информации.\n\t-\tРассмотрите инструмент для коммандной строки и библиотеку для Python [flowlogs-reader](https://github.com/obsrvbl/flowlogs-reader) для получения и работы с поточными логами VPC.\n- **IPv6** [доступен в VPC](https://aws.amazon.com/blogs/aws/new-ipv6-support-for-ec2-instances-in-virtual-private-clouds/). Наряду с этим объявлением, прошло представление [Интернет шлюза только-на-исход(Egress-Only Internet Gateway)](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/egress-only-internet-gateway.html). В тех случаях, когда можно использовать шлюзы NAT для включения только исходящего трафика для их VPC в IPv4, можно использовать интернет шлюз только-на-исход только для той же цели в IPv6.\n\n-\tПо вашему запросу Amazon предоставляет блок CIDR IPv6 для вашего VPC - в настоящее время вы не можете подключить свой собственный блок IPv6, если так случилось, что он у вас уже есть.\n-\tНовые и существующие VPC могут использовать IPv6. Существующие VPC должны быть настроены так, чтобы с ними ассоциировался блок CIDR IPv6, также, как и в новых VPC.\n\n### PrivateLink\n- 📒[Домашняя страница](https://aws.amazon.com/privatelink/) ∙ [Руководство пользователя](https://docs.aws.amazon.com/vpc/latest/userguide/vpce-interface.html) ∙  [Расценки](https://aws.amazon.com/privatelink/pricing/)\n- Одним из способов применения Private link является [интерфейс конечных точек VPC](https://docs.aws.amazon.com/vpc/latest/userguide/vpce-interface.html) который разворачивает ENI в вашем VPC и подсетях, что позволяет получить прямой доступ к API AWS таким образом, как если бы они были бы доступны локально в вашем VPC без необходимости выхода в интернет.\n- Другим вариантом использования является возможность открытия вашего сервиса другим учетным записям AWS через [сервис конечных точек VPC(VPC Endpoint Service)](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-service.html)\n\n### Ошибки и ограничения, связанные с VPC и сетевой безопасностью\n-\t🔸VPC привязаны к одному региону в одной учетной записи. Подсети привязаны к одному VPC и ограничены одной зоной доступности.\n-\t🔸Группы безопасности привязаны к одному VPC. Если вы используете инфраструктуру в нескольких VPC, вы должны убедиться, что ваши инструменты конфигурации/развертывания учитывают это.\n-\t🔸[Конечные точки VPC](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-endpoints.html) на текущий момент доступны только для S3 и DynamoDB. Если требования безопасности включают необходимость блокировки исходящего траффика с вашей VPC, возможно вы захотите воспользоваться [DNS фильтрацией](https://aws.amazon.com/blogs/security/how-to-add-dns-filtering-to-your-nat-instance-with-squid/) для контроля исходящего траффика к другим сервисам.\n-\t❗Будьте аккуратны при выборе CIDR блока ip-адресов для VPC: Если вам будет необходимо использовать [ClassicLink](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html), убедитесь, что ваш частный диапазон IP-адресов [не пересекается](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html#classiclink-limitations) с диапазоном EC2 Classic.\n-\t❗Если вы собираетесь соединение между VPC, тщательно изучите стоимость [передачи данных между VPC](https://aws.amazon.com/vpc/faqs/#Peering_Connections), так как для отдельных рабочих нагрузок и интеграций, она может быть чрезмерно дорогой.\n- ❗Для новых инстансов RDS требуется [группа подсетей](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.WorkingWithRDSInstanceinaVPC.html#USER_VPC.Subnets) в вашем VPC. Если вы используете [VPC по умолчанию](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/default-vpc.html), это не будет проблемой, так как VPC содержит подсеть для каждой зоны доступности в вашем регионе. В любом случае, если вы создаете свой VPC и планируете использование RDS, убедитесь, что у вас есть как минимум две подсети в VPC, чтобы выступать в виде группы подсетей.\n-\t❗Если вы удалили VPC по умолчанию, вы можете [пересоздать через CLI или через консоль](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/default-vpc.html#create-default-vpc).\n-\t❗Будьте крайне аккуратны с учетными данными VPN для подключения к VPC! Если они потеряны или скомпроментированы, конечная точка VPN должна быть удалена и пересоздана. Ознакомьтесь с инструкцией по [замене скомпроментированных учетных данных](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_VPN.html#CompromisedCredentials).\n-\t❗Группы безопасности и таблицы маршрутов применяют записи отдельно для IPv4 и IPv6, поэтому необходимо убедиться, что  записи добавлены для обоих протоколов соответственно.\n- \t💸Управляемый шлюзы NAT это удобная альтернатива управляемому вручную [инстансу NAT](https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPCNATInstance.html), но они тарифицируются погигабайтно. Рассмотрите [альтернативные варианты](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-comparison.html) если вы передаете много терабайт из частных подсетей в интернет. Если вы передаете терабайты/петабайты данных с инстансов EC2 из частных подсетей в S3, избегайте [оплаты за обработку данных шлюзом NAT](https://aws.amazon.com/vpc/pricing/) путем установки шлюзовой конечной точки VPC и направляйте траффик в/из S3 через эту конечную точку, вместо того, чтобы пересылать данные через шлюз NAT.\n\nKMS\n---\n\n### Основы KMS\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/kms/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/kms/latest/developerguide/) ∙ [ЧаВо](https://aws.amazon.com/kms/faqs/) ∙ [Расценки](https://aws.amazon.com/kms/pricing/)\n-\t**KMS** (Сервис управления ключами(Key Management Service)) это безопасный сервис для создания, хранения и аудита использования криптографических ключей.\n- **Интеграция сервисов:** KMS [интегрируется с другими сервисами AWS ](http://docs.aws.amazon.com/kms/latest/developerguide/service-integration.html): EBS, Elastic Transcoder, EMR, Redshift, RDS, SES, S3, WorkMail и Workspaces.\n- **API шифрования:** [API шифровать](http://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) и [API дешифровать API](http://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) позволяют вам зашифровывать и расшифровывать данные на стороне сервиса KMS, никогда не раскрывая содержимого мастер ключа.\n- **Ключи данных:** API [GenerateDataKey](http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys) генерирует новый ключ с мастер ключа. Содержимое ключа данных доступно вам, поэтому вы можете использовать его для шифрования и дешифрования данных любого уровня на уровне приложения. KMS не хранит, не управляет и не отслеживает ключи данных, вы несете ответственность за это в своем приложении.\n- 🔹**Аудит использования:** Настройте CloudTrail для аудита вызовов API KMS.\n- **Доступ:** Используйте [политики ключей(key policies)](http://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html) и [политики IAM ](http://docs.aws.amazon.com/kms/latest/developerguide/iam-policies.html) для предоставления различного уровня доступов к KMS. Например, вы можете создать политику IAM которая только [позволяет пользователю шифровать и расшифровывать данные с конкретным ключем](http://docs.aws.amazon.com/kms/latest/developerguide/iam-policies.html#iam-policy-example-encrypt-decrypt-specific-cmks).\n\n### Советы по KMS\n\n-\t🔹В компаниях очень распространено полное управление ключами с помощью собственных механизмов, но с самого начала гораздо предпочтительнее использовать такие службы, как KMS, так как это способствует более безопасному проектированию и улучшает политики и процессы управления ключами.\n-\tХорошая мотивация и обзор в [этой презентации от AWS](http://www.slideshare.net/AmazonWebServices/encryption-and-key-management-in-aws).\n-\tДетальная информация о криптографии [в этой белой книге от AWS](https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf).\n-\t[Эта публикация от Convox](https://convox.com/blog/encryption-at-rest) демонстрирует, почему и как использовать KMS для шифрования при хранении.\n\n### Ошибки и ограничения, связанные с KMS\n\n-\t🔸 Encrypt API работает только с данными < 4KB. Большие объемы данных требуют создания и использования[ключа данных](http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys) на уровне приложения.\n-\t🔸Аудит событий KMS не доступен через [CloudTrail Lookup Events API](http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_LookupEvents.html). Их можно посмотреть в сырых файлах .json.gz, которые CloudTrail сохраняет в S3.\n-\t🔸Чтобы зашифровать загрузку нескольких частей на S3, политика ключей KMS должна разрешать “kms:Decrypt” и “kms:GenerateDataKey*” в дополнение к “kms:Encrypt”, иначе загрузка закончится неудачей с ошибкой “AccessDenied”.\n-\t🔸Ключи KMS зависят от региона - они хранятся и могут использоваться только в том регионе, в котором они созданы. Их нельзя перенести в другие регионы.\n-\t🔸Ключи KMS имеют политику ключей, которая должна предоставлять доступ к чему-либо для управления ключом. Если вы не предоставляете доступ к ключу при создании, вам нужно обратиться в службу поддержки, чтобы сбросить политику ключа [снизьте риски того, что ключ станет неуправляемым](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html#key-policy-default-allow-root-enable-iam).\n-\t🔸Если вы используете политику ключей для предоставления доступа ролям или пользователям IAM, а затем удаляете пользователя/роль, воссоздание пользователя или роли не вернет разрешение на ключ.\n\n\nCloudFront\n----------\n\n### Основы CloudFront \n\n-\t📒 [Домашняя страница](https://aws.amazon.com/cloudfront/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/) ∙ [ЧаВо](https://aws.amazon.com/cloudfront/faqs/) ∙ [Расценки](https://aws.amazon.com/cloudfront/pricing/)\n-\t**CloudFront** это [сеть доставки контента (CDN)](https://en.wikipedia.org/wiki/Content_delivery_network) в AWS.\n-\tЕго основное назначение - снижение задержки для конечных пользователей за счет доступа к кэшируемому контенту путем размещения его в [более чем 60 глобальных выходных точках(edge location)](http://aws.amazon.com/cloudfront/details/).\n\n### Альтернативы CloudFront и привязки\n\n-\t🚪Рынок CDN [сильно фрагментирован](https://www.datanyze.com/market-share/cdn/). CloudFront был создан, чтобы быть лидером, но есть много альтернатив, которые могут лучше удовлетворить конкретные потребности.\n\n### Советы по CloudFront\n\n-\t🐥**IPv6** [поддерживается](https://aws.amazon.com/about-aws/whats-new/2016/10/ipv6-support-for-cloudfront-waf-and-s3-transfer-acceleration/). Это конфигурируемая настройка и она включена по умолчанию на каждой новой распределенной раздаче контента CloudFront. Поддержка IPv6 также распространяется на использование WAF с CloudFront.\n-\t🐥**HTTP/2** [теперь поддерживается](https://aws.amazon.com/about-aws/whats-new/2016/09/amazon-cloudfront-now-supports-http2/)! Клиенты [должны поддерживать TLS 1.2 и SNI](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesSupportedHTTPVersions).\n-\tВ то время, как в основном пользователи просматривают и скачивают контент (методы GET или HEAD), CloudFront также поддерживает ([с 2013 года0](https://aws.amazon.com/blogs/aws/amazon-cloudfront-content-uploads-post-put-other-methods/)) загрузку данных (POST, PUT, DELETE, OPTIONS, и PATCH).\n\t-\tВы должны подключить эти методы, указав [разрешенные HTTP методы](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesAllowedHTTPMethods) когда вы создаете раздачу.\n\t-\tЧто интересно, стоимость приема (загруженных) данных [обычно ниже](https://aws.amazon.com/cloudfront/pricing/), нежели за отправку (скачанных) данных.\n-\tВ базовой версии CloudFront [поддерживает SSL](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html) через [расширение TLS - SNI](https://en.wikipedia.org/wiki/Server_Name_Indication), которое поддерживается всеми современными веб-браузерами. Если вам необходимо поддерживать старые браузеры, вы будете вынуждены платить несколько сотен долларов за выделенные IP адреса.\n\t-\t💸⏱Помните, что инвалидация требует осторожности. CloudFront [поддерживает инвалидацию](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html) объектов с пограничных точек(edge locations), но обычно требуется какое-то количество времени на обработку запроса на всех пограничных точках и стоит $0.005 за запрос, после первой 1000 запросов. (Некоторые другие CDN работают лучше в этом плане.)\n-\tВ наши дни все должны использовать TLS, если это возможно. [Таблица Ильи Григорика](https://istlsfastyet.com/#cdn-paas) предлагает хороший обзор  возможностей, касающихся производительности TLS в CloudFront.\n-\tАльтернативой инвалидации, которой часто проще и быстрее управлять, является настройка раздачи на [кэширование со строками запросов](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/QueryStringParameters.html) и последующего добавления уникальных строк запросов с версиями к ресурсам, которые часто обновляются.\n-\t⏱Для хорошей производительности, рекомендуется [включить сжатие](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html) на раздачах CloudFront если источником выступает S3 или другой источник, которые содержит несжатый контент.\n\n### Ошибки и ограничения, связанные с CloudFront\n\n-\t🔸Если вы используете S3 в качестве резервного хранилища, помните, что конечные точки для хостинга веб-сайтов и для общего S3 разные. Например: “bucketname.s3.amazonaws.com” - это конечная точка для стандартного, но, чтобы иметь поддержку перенаправления и страниц ошибок, вам необходимо использовать конечную точку для опции хостинга вебсайтов, например, “bucketname.s3-website-us-east-1.amazonaws.com” (ну или соответствующего региона).\n-\t🔸По умолчанию, CloudFront не пересылает заголовки 'HTTP Host:' к вашим источникам. Это может быть проблематично для вашего источника, если вы запускаете несколько сайтов, переключаемых заголовками хостов. Вы можете [включить пересылку заголовков хоста](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#request-custom-headers-behavior) в настройках поведения кэширования по умолчанию.\n-\t🔸4096-битные SSL сертификаты: CloudFront не поддерживает 4096-битные SSL сертификаты по состоянию на 2016 год. Если вы используете SSL сертификат выпущенный третьей стороной, вам необходимо удостовериться, что он 2048-битный. Больше информации в [продолжающемся обсуждении](https://forums.aws.amazon.com/thread.jspa?threadID=148783).\n- Несмотря на то, что соединения от клиентов на пограничные сервера CloudFront могут использовать IPv6, [соединение с сервером источником будет продолжать использовать IPv4.](https://aws.amazon.com/about-aws/whats-new/2016/10/ipv6-support-for-cloudfront-waf-and-s3-transfer-acceleration/)\n\nDirectConnect\n-------------\n\n### Основы DirectConnect\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/directconnect/) ∙ [Руководство пользователя](http://docs.aws.amazon.com/directconnect/latest/UserGuide/) ∙ [ЧаВо](https://aws.amazon.com/directconnect/faqs/) ∙ [Расценки](https://aws.amazon.com/directconnect/pricing/)\n-\t**Direct Connect** это частное, выделенное соединение с вашей сети в AWS.\n\n### Советы по DirectConnect\n\n-\tЕсли ваш дата-центр имеет [партнерские отношения](https://aws.amazon.com/directconnect/partners/) с AWS, установка канала крайне упрощена.\n-\tИспользуйте для гарантированной производительности и целостности сети (**1 Gbps** или **10 Gbps** на канал).\n-\tИспользуйте чтобы связать  ко-локейшн, корпоративную или физическую сеть датацентра с вашей VPC. \n\t-\tПример: Растянуть корпоративный LDAP и/или Kerberos на инстансы EC2, запущенные в VPC.\n\t-\tПример: Сделать сервисы, которые размещены вне AWS по финансовым, нормативным или наследственным причинам, доступными из VPC.\n\nRedshift\n--------\n\n### Основы Redshift\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/redshift/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/redshift/latest/dg/) ∙ [ЧаВо](https://aws.amazon.com/redshift/faqs/) ∙ [Расценки](https://aws.amazon.com/redshift/pricing/)\n-\t**Redshift** это управляемое AWS [хранилище данных](https://en.wikipedia.org/wiki/Data_warehouse), которое предоставляет возможности параллельной работы, масштабируемости и является столбчатым хранилищем. Он очень широко используется. Он [был создан](https://en.wikipedia.org/wiki/Amazon_Redshift) используя технологию [ParAccel](https://en.wikipedia.org/wiki/ParAccel) и предоставляет [Postgres](https://en.wikipedia.org/wiki/PostgreSQL)-совместимые интерфейсы.\n\n### Альтернативы Redshift и привязки\n\n-\t⛓🚪Какое бы хранилище данных вы ни выбрали, ваш бизнес, вероятно, будет завязан на него на долгое время. Также (и не случайно) рынок хранилищ данных сильно фрагментирован. Выбор хранилища данных - это выбор, который нужно сделать осторожно, с исследованием и осознанием [рыночного ландшафта](https://www.datanami.com/2016/03/14/data-warehouse-market-ripe-disruption-gartner-says/) а также с учетом инструментов [бизнес аналитики](https://en.wikipedia.org/wiki/Business_intelligence), которые вы планируете использовать.\n\n### Советы по Redshift\n\n-\tХотя Redshift в основном Postgres-совместим, его SQL диалект и профили производительности отличаются.\n-\tRedshift поддерживает только [12 примитивных типов данных](https://docs.aws.amazon.com/redshift/latest/dg/c_Supported_data_types.html). ([Список неподдерживаемых типов Postgres](https://docs.aws.amazon.com/redshift/latest/dg/c_unsupported-postgresql-datatypes.html)\\)\n-\tОн имеет ноду-лидер и вычислительные ноды (лидер распределяет запросы по вычислительным). Обратите внимание, что некоторые функции [могут выполняться только на лидерской ноде.](https://docs.aws.amazon.com/redshift/latest/dg/c_SQL_functions_leader_node_only.html)\n-\t🔹Обязательно создайте новую [группу параметров кластера](http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html) и группу опций базы данных, так как группа параметров по умолчанию не позволяет динамических изменений конфигурации.\n-\tОсновные сторонние инструменты BI поддерживают интеграцию с Redshift (Прочтите публикацию [Quora](https://www.quora.com/Which-BI-visualisation-solution-goes-best-with-Redshift)).\n-\t[Top 10 Performance Tuning Techniques for Amazon Redshift](https://blogs.aws.amazon.com/bigdata/post/Tx31034QG0G3ED1/Top-10-Performance-Tuning-Techniques-for-Amazon-Redshift) предоставляет превосходный список методов настройки производительности.\n-\t[Amazon Redshift Utils](https://github.com/awslabs/amazon-redshift-utils) содержит полезные утилиты, скрипты и представления для упрощения работы с Redshift.\n-\tЗапускайте [VACUUM](http://docs.aws.amazon.com/redshift/latest/dg/t_Reclaiming_storage_space202.html) регулярно после большого количества удалений или обновлений, чтобы освободить пространство и повысить производительность запросов.\n-\tИзбегайте выполнения всеховатывающих команд[VACUUM](http://docs.aws.amazon.com/redshift/latest/dg/r_VACUUM_command.html) или [ANALYZE](http://docs.aws.amazon.com/redshift/latest/dg/r_ANALYZE.html) на уровне кластера. Проверки каждой таблицы для определения необходимости выполнения действия VACUUM или ANALYZE ресурсоемки. Выполняйте команды ANALYZE и VACUUM на тех объектах, которым это требуется. Используйте [Analyze & Vacuum Schema Utility](https://github.com/awslabs/amazon-redshift-utils/tree/master/src/AnalyzeVacuumUtility) чтобы сделать это. SQL-запрос для определения необходимости выполнения команд VACUUM или ANALYZE для таблицы, может быть найден тут - [Schema Utility README](https://github.com/awslabs/amazon-redshift-utils/blob/master/src/AnalyzeVacuumUtility/README.md), если вам необходимо создать собственный процесс обслуживания.\n-\tRedshift предлагает различные варианты [сжатия столбцов](http://docs.aws.amazon.com/redshift/latest/dg/t_Compressing_data_on_disk.html) чтобы оптимизировать размер хранимых данных. AWS настоятельно рекомендует пользователям использовать [автоматическое сжатие](http://docs.aws.amazon.com/redshift/latest/dg/c_Loading_tables_auto_compress.html) на стадии [COPY](https://docs.aws.amazon.com/redshift/latest/dg/r_COPY.html), когда Redshift использует выборку данных для анализа параметров сжатия столбцов. В любом случае, автоматическое сжатие может быть применено только к пустой таблице, без каких либо данных. Поэтому убедитесь, что исходный пакет загрузки достаточно большой, чтобы предоставить Redshift репрезентативную выборку данных (размер выборки по умолчанию составляет 100 000 строк).\n-\tRedshift использует столбцовое хранилище, следовательно, у него нет возможностей индексирования. В любом случае вы можете использовать [distribution key](http://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-best-dist-key.html) и [sortkey](http://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-sort-key.html) для повышения производительности. Redshift имеет два типа ключей сортировки: составной ключ сортировки и чередующийся ключ сортировки.\n-\tСоставной ключ сортировки составлен из всех столбцов, перечисленных в определении ключа сортировки. Это наиболее полезно, когда у вас есть запросы с операциями с использованием префикса ключа сортировки.\n-\tС другой стороны, чередующийся ключ сортировки дает одинаковый вес каждому столбцу или подмножеству столбцов в ключе сортировки. Поэтому, если вы заранее не знаете, какие столбцы нужно выбрать для сортировки и фильтрации, это гораздо лучший выбор, чем составной ключ. [Тут](https://aws.amazon.com/blogs/aws/quickly-filter-data-in-amazon-redshift-using-interleaved-sorting/) пример чередующегося ключа сортировки.\n-\t🔸⏱ **Стратегии распределения:** Поскольку данные в Redshift физически распределяются между узлами, выбор правильного **ключа распределения** данных и [стиля распределения](http://docs.aws.amazon.com/redshift/latest/dg/c_choosing_dist_sort.html) является критичным для адекватной производительности запросов. Существуют три возможных выбора стиля распределния — **EVEN** (по умолчанию), **KEY** или **ALL**. Используйте KEY, чтобы сопоставить столбцы join key для таблиц, которые объединены в запросы. Используйте ALL для того, чтобы поместить данные в маленькие таблицы на всех нодах кластера.\n\n### Ошибки и ограничения, связанные с Redshift\n\n-\t❗⏱Хотя Redshift может хорошо обрабатывать тяжелые запросы, он не масштабируется по горизонтали, то есть не обрабатывает несколько запросов параллельно. Поэтому, если вы ожидаете высокую параллельную нагрузку, рассмотрите возможность репликации или (если возможно) разделения ваших данных между несколькими кластерами.\n-\t🔸 Лидер-нода, которая управляет связью с клиентскими программами и всей связью с вычислительными узлами, является единой точкой отказа.\n-\t⏱Хотя большинство запросов Redshift хорошо распараллеливаются на уровне вычислительных узлов, на лидер-ноде выполняются определенные этапы, которые могут стать узким местом.\n-\t🔹Транзакции передачи данных Redshift очень дороги и запускаются сериями на уровне кластера. Поэтому, по возможности, рассмотрите возможность группировки нескольких команд изменения (COPY/INSERT/UPDATE) в одну транзакцию, когда это возможно.\n-\t🔹Redshift не поддерживает развертывания в нескольких зонах доступности. Построение кластеров в нескольких зонах доступности не является  чем-то простым. [Тут](https://blogs.aws.amazon.com/bigdata/post/Tx13ZDHZANSX9UX/Building-Multi-AZ-or-Multi-Region-Amazon-Redshift-Clusters) есть пример с использованием Kinesis.\n-\t🔸Остерегайтесь хранить несколько небольших таблиц в Redshift. Способ размещения таблиц Redshift на диске делает его непрактичным. Минимальное место на диске необходимое для хранения таблицы (в MB) равно `nodes * slices/node * columns`. Например, в кластере из 16 нод, пустая таблица с 20 столбцами займет 640MB.\n-\t⏱ Производительность запросов значительно снижается во время получения данных. Настройки [WLM (Workload Management)](http://docs.aws.amazon.com/redshift/latest/dg/c_workload_mngmt_classification.html) помогают в некоторой степени. Однако, если вам нужна стабильная производительность чтения, подумайте о наличии реплики кластера (за дополнительную плату) и переключите их во время обновления.\n-\t❗ Никогда не изменяйте размер живого кластера. Операция изменения размера может занять несколько часов в зависимости от размера набора данных. В редких случаях операция также может зависнуть и, в итоге, у вас будет нефункциональный кластер. Более безопасный подход - создать новый кластер из снапшота, изменить размер нового кластера и удалить старый.\n-\t🔸Redshift имеет **зарезервированные ключевые слова**, которых нет в Postgres (полный список [тут](https://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html)). Остерегайтесь DELTA ([Delta Encodings](https://docs.aws.amazon.com/redshift/latest/dg/c_Delta_encoding.html)).\n-\t🔸Redshift не поддерживает многие функции Postgres, особенно несколько функций, связанных с датой/временем и агрегацией. Смотрите [полный список тут](https://docs.aws.amazon.com/redshift/latest/dg/c_unsupported-postgresql-functions.html).\n-\t🔸 Ограничения уникальности, первичного ключа и внешнего ключа для таблиц Redshift носят исключительно информативный характер и не применяются. Однако они используются оптимизатором запросов для создания планов запросов. Ограничения для столбцов `NOT NULL` применяются. Смотрите [тут](https://docs.aws.amazon.com/redshift/latest/dg/t_Defining_constraints.html) для получения большей информации об ограничениях.\n-\t🔸Сжатие ключа сортировки [может привести к значительному снижению производительности](https://aws.amazon.com/blogs/big-data/optimizing-for-star-schemas-and-interleaved-sorting-on-amazon-redshift/). Таким образом, если ваши запросы Redshift, включающие ключи сортировки, являются медленными, вам стоит рассмотреть возможность снятия сжатия для ключа сортировки.\n-\t🔹 [Выбор ключа сортировки](http://docs.aws.amazon.com/redshift/latest/dg/t_Sorting_data.html) очень важен, так как вы не сможете сменить ключ сортировки таблицы после создания. Если вам необходимо сменить ключ сортировки или распределения для таблицы, вам необходимо будет создать новую таблицу с новыми ключами и перенести данные запросом типа “insert into new_table select * from old_table”.\n-\t❗🚪 Когда переносите данные запросом типа “insert into x select from y”, вам потребуется иметь в два раза больше дискового пространства, чем таблица “y” занимает на дисках в кластере. Redshift сначала копирует данные на диск, а только потом в новую таблицу.[Здесь](https://www.periscopedata.com/blog/changing-dist-and-sort-keys-in-redshift.html) хорошая статья о том, как это происходит с большими таблицами.\n\nEMR\n---\n\n### Основы EMR\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/emr/) ∙ [Информация о выпуске](http://docs.aws.amazon.com/ElasticMapReduce/latest/ReleaseGuide/) ∙ [ЧаВо](https://aws.amazon.com/emr/faqs/) ∙ [Расценки](https://aws.amazon.com/emr/pricing/)\n-\t**EMR** (раньше обозначал Elastic Map Reduce, но не теперь, поскольку теперь он далеко выходит за пределы функции map-Reduce) - это сервис, который предлагает управляемое развертывание [Hadoop](https://en.wikipedia.org/wiki/Apache_Hadoop), [HBase](https://en.wikipedia.org/wiki/Apache_HBase) и [Spark](https://en.wikipedia.org/wiki/Apache_Spark). Он уменьшает бремя самостоятельного управления и настройки этих сервисов. \n\n### Альтернативы EMR и привязки\n\n-\t⛓Большая часть EMR основана на технологии с открытым исходным кодом, которую вы, в принципе, можете развернуть самостоятельно. Однако рабочие процессы и многие другие инструменты зависят от AWS. Переход от EMR к вашим собственным кластерам возможен, но не всегда тривиален.\n\n### Советы по EMR\n\n-\tEMR опирается на многие версии Hadoop и другого вспомогательного программного обеспечения. Не забудьте проверить [какие версии используются](https://docs.aws.amazon.com/ElasticMapReduce/latest/ReleaseGuide/emr-release-components.html).\n-\t⏱Развернутые EMR и Hadoop могут иметь значительный оверхэд по сравнению с эффективным процессингом на одной машие. Если у вас немного данных и производительность имеет значение, вам стоит рассмотреть альтернативы, как например в этой [публикации](http://aadrake.com/command-line-tools-can-be-235x-faster-than-your-hadoop-cluster.html).\n-\tРазработчики на Python также могли б обратить внимание на [mrjob](https://github.com/Yelp/mrjob) от Yelp.\n-\tТребуется определенное время для тонкой настройки производительности задач EMR, именно поэтому сторонние сервисы, такие как [Qubole’s data service](https://www.qubole.com/mapreduce-as-a-service/) завоевывают популярность, как метод повышения производительности и снижения затрат.\n\n### Ошибки и ограничения, связанные с EMR\n\n-\t💸❗**Затраты на EMR** могут быстро накапливаться, так как используется множетсво инстансов,  кроме того, эффективность может быть низкой, в зависимости от конфигурации кластера и выбора рабочих нагрузок, кроме того, инциденты вроде зависших задач могут быть весьма дорогостоящими. Посмотрите[раздел управления затратами EC2](#управление-затратами-на-ec2), особенно советы относительно спотовых инстансов. [Эта публикация](https://aws.amazon.com/blogs/big-data/strategies-for-reducing-your-amazon-emr-costs/) также дает дополнительные советы, однако была написана до перехода на посекундную тарификацию.\n-\t💸 Опасайтесь “двойных затрат”. С EMR вы платите за вычислительную емкость EC2 и сервисные платежи. В дополнение, EMR синхронизирует логи задач с S3, что означает, что вы платите за хранилище и **PUT запросы** по [расценкам S3 standard](https://aws.amazon.com/s3/pricing/#Request_Pricing). Хотя лог файлы имеют обыкновение быть относительно мелкими, каждая задача Hadoop, в зависимости от размера генерирует тысячи лог файлов, которые легко могут накинуть тысячи долларов к вашему счету от AWS. [Аггрегация логов  YARN](http://hortonworks.com/blog/simplifying-user-logs-management-and-access-in-yarn/) не доступна в EMR.\n\nKinesis Streams\n---\n\n### Основы Kinesis Streams\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/kinesis/streams/) ∙ [Руководство разработчика](https://docs.aws.amazon.com/streams/latest/dev/introduction.html) ∙ [ЧаВо](https://aws.amazon.com/kinesis/streams/faqs/) ∙ [Расценки](https://aws.amazon.com/kinesis/streams/pricing/)\n-\t**Kinesis Streams** (который ранее назывался просто Kinesis, до выхода Kinesis Firehose и Kinesis Analytics) - это сервис, который позволяет вам использовать высокопроизводительные потоки данных для немедленной или отложенной обработки другими сервисами AWS.\n- Субкомпонентны Kinesis Streams называются [**шарды(shards)**](https://docs.aws.amazon.com/streams/latest/dev/key-concepts.html). Каждый шард предоставляет возможность записи со скоростью 1MB/s и чтения со скоростью 2MB/s с максимальной частотой 5 операций чтения в секунду. Шарды в потоке можно уменьшать и увеличивать программно на основе множества метрик.\n- Всем записям, введенным в Kinesis Stream, присваивается уникальный порядковый номер по мере их получения. Записи в потоке упорядочены по этому номеру, поэтому любой порядок времени сохраняется.\n- [На этой странице](http://docs.aws.amazon.com/streams/latest/dev/key-concepts.html) обобщаются ключевые понятия и концепции Kinesis Streams.\n\n### Альтернативы Kinesis Streams и привязки\n\n-\t🚪 Kinesis наиболее сравним с [Apache Kafka](https://kafka.apache.org/), решением по приему данных с открытым кодом. Возможно развернуть кластер Kafka на [инстансах EC2](#ec2) (или любом другом VPS), в любом случае вы будете нести ответственность за управление и поддержку как Zookeeper, так и Kafka в высокодоступной конфигурации. Confluent опубликовали хорошую статью с их рекомендациями, как это сделать [тут](http://www.confluent.io/blog/design-and-deployment-considerations-for-deploying-apache-kafka-on-aws/), внизу есть ссылки на несколько других блогов, которые они написали на эту тему.\n-\t⛓ Kinesis использует очень AWS-специфичные API, так что вы должны быть в курсе потенциальных будущих затрат по обратной миграции, если вы выберете его. \n-\tПриложение, которое эффективно использует Kinesis Streams, будет масштабировать количество шардов вверх и вниз в зависимости от требуемой пропускной способности. (Имейте ввиду, что прямого эвкивалента этому в Apache Kafka нет.)\n\n\n### Советы по Kinesis Streams\n\n-\t[KCL](https://docs.aws.amazon.com/streams/latest/dev/developing-consumers-with-kcl.html) (Библиотека клиента Kinesis(Kinesis Client Library))предоставляет скелетный интерфейс для программ на Java, Node, Python, Ruby и .NET, которые легко используют данные из потока Kinesis. Чтобы начать использовать данные из потока, вам нужно только предоставить файл конфигурации, указывающий на правильный поток Kinesis, и функции для инициализации потребителя, обработки записей и выключения потребителя.\n\t- KCL использует таблицу DynamoDB для отслеживания обработанных записей. Это гарантирует, что все записи обрабатываются “хотя бы раз”. Заботой программиста является необходимость удостовериться, что программа может обрабатывать дважды обработанные записи.\n\t- KCL также использует DynamoDB для отслеживания других “воркеров” KCL. Он автоматически распределяет доступные шарды Kinesis между всеми воркерами поровну.\n\n### Ошибки и ограничения, связанные с Kinesis Streams\n\n- 🔸⏱  Каждый шард Kinesis Streams позволяет совершать [5 операций чтения в секунду](http://docs.aws.amazon.com/streams/latest/dev/service-sizes-and-limits.html). Если вы равномерно распределяете данные по множеству шардов, ваш предел частоты чтения для потока останется на уровне 5 операций чтения в секунду в совокупности, поскольку каждое приложение-потребитель должно будет проверять каждый отдельный шард на наличие новых записей. Это накладывает жесткое ограничение на количество различных приложений-потребителей, возможных на поток, из-за данной максимальной задержки чтения.\n   - Например, если у вас есть 5 приложений-потребителей, считывающих данные из одного потока с любым количеством шардов, они не могут читать с задержкой менее одной секунды, поскольку каждому из 5 потребителей потребуется опрашивать *каждый шард* каждую секунду, достигая предела 5 операций чтения в секунду.\n\t- [Эта публикация](https://brandur.org/kinesis-in-production) является продолжением обсуждения производительности ии ограничений Kinesis в эксплуатации.\n-\t💸 **Kinesis Streams не включен в бесплатный уровень использования.** Убедитесь ,что вы отключили поток, если экспериментировали с ним в личном аккаунте, иначе это может привести к неожиданным издержкам (~$11 за шард-месяц.)\n\nKinesis Firehose\n---\n\n### Ошибки и ограничения, связанные с  Kinesis Firehose\n\n- 🔸 📜 Будучи пересылаемым с Firehose в Elasticsearch, документ в формате JSON не может содержать свойство “_id”. Firehose не будет пытаться доставить такие документы и в логах не будет отражено никаких ошибок. \n\n\nDevice Farm\n-----------\n\n### Основы Device Farm \n\n-\t📒 [Домашняя страница](https://aws.amazon.com/device-farm/) ∙ [Руководство разработчика](http://docs.aws.amazon.com/devicefarm/latest/developerguide/) ∙ [ЧаВо](https://aws.amazon.com/device-farm/faq/) ∙ [Расценки](https://aws.amazon.com/device-farm/pricing/)\n- **Device Farm** - это сервис AWS позволяющий тестировать мобильные приложения на реальных устройствах.\n- Поддерживает устройства на iOS и Android (включая Kindle Fire), также как и мобильный веб.\n- Поддерживает доступ к удаленным устройствам в целях обеспечения интерактивного тестирования/отладки.\n\n### Советы по Device Farm\n\n- [Блог AWS Mobile](https://aws.amazon.com/blogs/mobile/) содержит несколько примеров применения Device Farm для тестирования.\n- Device Farm предлагает бесплатный тестовый период для пользователей, которые хотят оценить свои сервисы.\n- Device Farm предлагает две ценовых модели: Оплата **за минуту использования устройства** полезна для случаев малого использования или для ситуаций, когда сложно предсказать объем использования. **Неограниченное тестирование** полезно в ситуациях, когда активное использование ожидается с самого начала.\n- Чтобы минимизировать время ожидания доступности устройств, одним из подходов является создание нескольких пулов устройств с разными устройствами, а затем случайный выбор одного из неиспользуемых пулов устройств при каждом запуске.\n\n### Ошибки и ограничения, связанные с Device Farm \n\n- ❗Устройства не имеют SIM-карт, следовательно не могут быть использованы для тестирования функций связанынх с SIM-картами.\n- 🔸Device Farm поддерживает тестирование для большинства популярных языков/фреймворков, но не для всех. Актуальный список поддерживаемых фреймворков и языков представлен на [этой странице](http://docs.aws.amazon.com/devicefarm/latest/developerguide/test-types-overview.html).\n- 🔸API и CLI Device Farm довольно таки низко-уровневый и может потребовать разработки дополнительных инструментов или скриптов поверх них.\n- 🔸AWS предоставляет несколько инструментов и плагинов для Device Farm, в любом случае это не покрывает все возможные случаи или платформы. Может потребоваться разработка специальных инструментов или плагинов для поддержки конкретных требований.\n- ❗В общем, Device Farm не имеет Android устройств от китайских компаний, таких как Huawei, Meizu, Lenovo, и т.д. Актуальный список поддерживаемого оборудования размещен [здесь](https://aws.amazon.com/device-farm/device-list/).\n- 🔸Доступность устройств неравномерна. Она зависит от нескольких факторов, включая популярность устройства. Обычно, более современные устройства подверженны большему спросу, таким образом время ожидание доступности для них будет выше, нежели для более старых устройств.\n\nMobile Hub\n----------\n\n### Основы Mobile Hub\n\n* 📒 [Домашняя страница](https://aws.amazon.com/mobile/) ∙ [Руководство пользователя](https://docs.aws.amazon.com/mobile-hub/latest/developerguide/) ∙ [ЧаВо](https://aws.amazon.com/mobile/faqs/) ∙ [Расценки](https://aws.amazon.com/mobile/pricing/)\n- **Mobile Hub** оркестрирует несколько сервисов для создания серверной части в AWS для мобильных и веб-приложений.\n- Каждый _проект_ в Mobile Hub имеет один _бэкенд_ состоящий из настраиваемых функций, и одно или более _приложений_.\n - Функции включают в себя Аналитику(Analytics), Облачную логику(Cloud Logic), Разговорных ботов(Conversational Bots), Хостинг и стриминг(Hosting and Streaming), Базы данных NoSQL(NoSQL Database), Хранилище пользовательских данных(User Data Storage) и Авторизацию пользователей(User Sign-In). Каждая функция использует один или два сервиса, для предоставления куска функциональности.\n - Используемые сервисы включают в себя, [API Gateway](#api-gateway), [CloudFront](#cloudfront), Cognito, [Device Farm](#device-farm), [DynamoDB](#dynamodb), [Lambda](#lambda), Lex, Pinpoint и [S3](#S3).\n - Существуют SDK для Android (Java), iOS (Swift), Web (JS) и React Native (JS). Также имеется CLI для приложений JavaScript.\n\n### Советы по Mobile Hub\n- [Консоль Mobile Hub](https://console.aws.amazon.com/mobilehub/home#/) содержит наборы для старта и учебные пособия для различных платформ.\n- CLI позволяет проводить локальную разработку Lambda-кода (по умолчанию на JS) с использованием команд `awsmobile {pull|push}` для синхронизации локальной папки с облаком и обратно.\n- Mobile Hub сам по себе бесплатен, но каждый используемый сервис имеет свою модель оплаты и расценок.\n\n### Ошибки и ограничения, связанные с Mobile Hub\n- 🔸Функция Cloud API позволяет импортировать существующую функцию Lambda вместо определения новой, но с CLI есть некоторые косяки. Для подробной информации смотрите в GitHub [issues](https://github.com/aws/awsmobile-cli/issues).\n- ❗Mobile Hub использует CloudFormation под капотом и сильно тупит, когда сервис меняется вне консоли Mobile Hub.\n\nIoT\n---\n\n### Основы IoT\n\n* \t📒 [Домашняя страница](https://aws.amazon.com/iot/) ∙ [Руководство пользователя](https://docs.aws.amazon.com/iot/latest/developerguide/) ∙ [ЧаВо](https://aws.amazon.com/iot/faqs/) ∙ [Расценки](https://aws.amazon.com/iot/pricing/)\n- \t**IoT** - это платформа, позволяющая клиентам, таким как устройства IoT или программные приложения ([примеры](http://internetofthingswiki.com/iot-applications-examples/541/)) связываться с облаком AWS.\n- \tКлиенты, также называемые **устройствами** (или **вещами**) включают в себя обширный диапазон различных типов устройств. В общем есть три категории типов устройств, которые могут взаимодействовать с сервисами IoT путем отсылки сообщений по IoT протоколу, используя брокер сообщений типа Pub/Sub, называемый IoT **Device Gateway**:\n    * \tТолько отправка сообщений: Как пример - [AWS IoT Button](https://aws.amazon.com/iot/button/) для  [маячка eddystone](http://developer.estimote.com/eddystone/).\n    * \tОтправка, прием и обработка сообщений: Например, простая плата обработки, типа **Raspberry Pi** ([руководство по быстрому старту](http://docs.aws.amazon.com/iot/latest/developerguide/iot-device-sdk-c.html)), или устройство Alexa, как например [Echo или Echo Dot](https://amazon.com/echo), которые спроектированы для работы с [AWS Alexa skills kit](https://developer.amazon.com/alexa-skills-kit) (программироуемые голосовой сервис от AWS).\n- \tУ AWS есть полезное [руководство по быстрому старту](http://docs.aws.amazon.com/iot/latest/developerguide/iot-gs.html) (используя консоль) и [слайдовая презентация](http://www.slideshare.net/AmazonWebServices/connecting-to-aws-iot) по базовым темам.\n* **Терминология IoT:**\n    * \tAWS [**IoT Things**](http://docs.aws.amazon.com/iot/latest/developerguide/iot-thing-management.html) (метаданные для устройств в хранятся в [реестре](http://docs.aws.amazon.com/iot/latest/developerguide/iot-thing-management.html)), а также позволяет хранить состояние устройства в документе формата JSON, который зовется [**тенью устройства(device shadow)**](http://docs.aws.amazon.com/iot/latest/developerguide/iot-thing-shadows.html).  Метаданные устройства также могут храниться в [**Типах вещей IoT(IoT Thing Types)**](http://docs.aws.amazon.com/iot/latest/developerguide/thing-types.html). Это помогает в управлении метаданными устройства, позволяя повторно использовать описание и конфигурацию устройства для более чем одного устройства. Имейте ввиду, что типы вещей IoT могут устаревать, но не меняться - они неизменны.\n    * \tAWS [**IoT Certificates**](http://docs.aws.amazon.com/iot/latest/developerguide/attach-cert-thing.html) (аутентификация устройств) - является логическим сопоставлением уникального сертификата логическому представлению устройства. Это сопоставление может быть сделано в консоли. Вдобавок, публичный ключ сертификата должен быть скопирован на физическое устройство. Это касается аутентификации устройств на конкретном шлюзе устройств AWS (Device Gateway) (брокере сообщений). Вы можете назначать IoT устройствам IoT сертификаты от AWS или вы можете [развернуть свой собственный центр сертификации CA (Certificate Authority) в AWS](http://docs.aws.amazon.com/iot/latest/developerguide/device-certs-your-own.html), выпускать свои собственные сертификаты и назначать эти сертификаты на устройства через консоль AWS или командную строку.\n    * \tAWS [**IoT Policies**](http://docs.aws.amazon.com/iot/latest/developerguide/authorization.html) (авторизация устройства/темы)- это файлы в формате JSON, которые ассоцииированы с одним или несколькими сертификатами AWS IoT. Таким образом назначенным устройствам разрешается публиковать и/или подписываться на сообщения из одного или более топиков MQTT.\n    * \tAWS [**IoT Rules**](http://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) являются SQL-подобными запросами, которые позволяют повторно использовать некоторые или все данные сообщений устройства, как описано в [этой презентации, в которой обобщаются шаблоны проектирования для правил IoT](http://www.slideshare.net/AmazonWebServices/programming-the-physical-world-with-device-shadows-and-rules-engine-66486454).\n    * \tПредставленная ниже [инфографика](https://aws.amazon.com/iot/how-it-works/) обобщает поток сообщений между сервисами AWS IoT:\n\n![Как работает AWS IoT](https://d0.awsstatic.com/IoT/diagrams/awsiot-how-it-works_HowITWorks_1-26.png \"Как работает AWS IoT\")\n\n### IoT Greengrass\n\n* 📒 [Домашняяя страница](https://aws.amazon.com/greengrass/)\n* 🐥**Greengrass** это программная платформа, которая расширяет возможности AWS IoT, позволяя выполнять функции Lambda непосредственно на локальных устройствах. Это также позволяет устройствам IoT иметь возможность безопасного обмена данными в локальной сети без необходимости подключения к облаку.\n    * Greengrass включает в себя локальный менеджер сообщений, который может буферизовать сообщения в случае потери связи, чтобы сохранить входящие и исходящие в облако сообщения. Лямбда-функции, развернутые локально, могут запускаться локальными событиями, сообщениями из облака или другими источниками.\n    * Greengrass включает безопасную аутентификацию и авторизацию устройств в локальной сети, а также между локальной сетью и облаком AWS. Он также обеспечивает безопасное обновление программного обеспечения функций Lambda.\n*  Greengrass включает в себя менеджер сообщений, окружение Lambda, локальная копия сервиса для теней устройств и агент для уплавления групповой конфигурацией Greengrass.\n* **Группы Greengrass(Greengrass groups)** - это контейнера, для настроек, подписок и назначенных лямбда функций для выбранных IoT устройств. В группе Greengrass устройство является либо ядром Greengrass, либо устройством IoT, которое будет подключено к этому конкретному ядру Greengrass.\n* Greengrass Core SDK позволяет функциям Lambda взаимодействовать с ядром AWS Greengrass, на котором они запускаются, чтобы публиковать сообщения, взаимодействуют с сервисом теней устройств, или вызывают другую развернутую функцию Lambda.\n* AWS Greengrass Core SDK поддерживает отправку только сообщений MQTT с QoS = 0.\n* Размещенное ниже [изображение](http://docs.aws.amazon.com/greengrass/latest/developerguide/what-is-gg.html) показывает архитектуру сервисов AWS IoT Greengrass:\n\n![IoT Greengrass](http://docs.aws.amazon.com/greengrass/latest/developerguide/images/greengrass.png)\n\n\n### Альтернативы IoT и привязки\n\n- \tAWS, Microsoft и Google имеют все представленные IoT-специфичные наборы облачных сервисов с конца 2015 года. AWS был первым, выведя свои сервисы IoT в [широкую доступность](https://aws.amazon.com/blogs/aws/aws-iot-now-generally-available/) в декабре 2015 года. Microsoft выпустили свой набор сервисов IoT в Azure в [феврале 2016 года](https://azure.microsoft.com/en-us/updates/generally-available-microsoft-azure-iot-hub/).  Google аннонсировал, но не выпустил свои IoT сервисы [Android Things](https://developer.android.com/things/index.html) и [Weave](https://developers.google.com/weave/).\n- \tПричинами возникновения привязки могут стать [протокола](http://www.postscapes.com/internet-of-things-protocols/) (для примера - MQTT, AMQP), формат сообщений(например JSON или Hex...) и безопасность (сертификаты).\n\n### Советы по IoT\n\n- \t**Начните с кнопок:** Одним из способов начать - является использование [**AWS IoT Button**](https://aws.amazon.com/iot/button/).  AWS предлагает большое число примеров кода для использования с их IoT кнопкой, вы можете зайти в консоль, кликнуть по ссылке “connect AWS IoT button”  и попадете в консоль AWS Lambda. Тут вы можете ввести серийный номер вашей кнопки для сопоставления с Lambda. (На момент написания данного текста, кнопки AWS IoT продавались только в США.)\n- \t**Соединения и протокола:** Важно понимать особенности устройств, которые вы хотите подключить к сервису AWS IoT,включая то, как вы будете обеспечивать безопасность соединения с устройством, протокола устройства и так далее. Поставщики облачных услуг существенно различаются в поддержке общих протоколов IoT, таких как MQTT, AMQP, XMPP. AWS IoT поддерживает **защищенный MQTT**, **WebSockets** и **HTTPS**.\n- \tПоддержка обработки сертификатов для **безопасности устройств** является ключевым отличием в этой области. В августе 2016, AWS добавило функцию [регистрации сертификатов точно-в-срок](https://aws.amazon.com/blogs/iot/just-in-time-registration-of-device-certificates-on-aws-iot/) для IoT устройств в своих сервисах.\n- \t**Совместно с другими сервисами:** Обычной практикой является совместное использования с другими сервисами AWS, такими как AWS Lambda, Kinesis и DynamoDB, хотя это не означает, что это обязательно. Образцы эталонных архитектур приложений IoT приведены в этом [скринкасте](https://www.youtube.com/watch?v=0Izh6ySpwb8/).\n- \t**Инструменты тестирования:**\n    *\tЧтобы было легко начать, AWS включило легковесный MQTT клиент в состав консоли AWS IoT. Тут вы можете создать и протестировать отправку и прием сообщений в различные топики MQTT и из них.\n    * \tПри локальном тестировании, при использовании MQTT, может быть полезно загрузить и использовать инструмент с открытым кодом [Mosquitto broker](https://mosquitto.org/download/) для локального тестирования с устройствами и/или симуляторами устройств.\n    * \tМожно использовать [симулятор загрузки MQTT](https://github.com/awslabs/aws-iot-mqtt-load-generator) для нагрузочного тестирования вашего IoT решения.\n\n### Ошибки и ограничения, связанные с IoT\n\n- \t🔸**Протокола IoT:** Очень важно убедиться в точной поддержке устройством типов протокола IoT для передачи сообщений. Для примера, один из наиболее используемых IoT протоколов - [MQTT](https://www.ibm.com/developerworks/community/blogs/5things/entry/5_things_to_know_about_mqtt_the_protocol_for_internet_of_things?lang=en). В MQTT существует [три возможных уровня QoS](https://dzone.com/articles/internet-things-mqtt-quality).  AWS IoT поддерживает MQTT [QoS 0] (http://docs.aws.amazon.com/iot/latest/developerguide/protocols.html) (запустить и забыть или не более одного раза) и QoS 1 (хотя бы один раз или включает подтверждение), но *не* QoS 2 (запустить ровно один раз, требуется 4-этапное подтверждение).  Это важно для понимания того, сколько кода вам придется написать для решения ваших конкретных задач.  Вот [презентация о ньюансах соединения](http://www.slideshare.net/AmazonWebServices/overview-of-iot-infrastructure-and-connectivity-at-aws-getting-started-with-aws-iot).\n- \t🔸Экосистема связующая политики IoT и ассоциированные с ними устройства с ролями и пользователями AWS IAM - незрелая. Дополнительная разработка в целях обеспечения требований безопасности является обычной практикой.\n- \t❗Частой ошибкой является непонимание важности **безопасности** IoT **устройств**.  Необходимо назначить уникальный сертификат (публичный ключ) на *каждое* устройство. Вы можете выпустить свои сертификаты и загрузить их в AWS или вы можете использовать выпущенные AWS сертификаты IoT устройств. Было бы великолепно прочесть и понять собственное руководство AWS по этой [теме](http://www.slideshare.net/AmazonWebServices/best-practices-of-iot-in-the-cloud).\n- \t🔸Может быть только один **AWS IoT Gateway** (точка подключения) на один AWS аккаунт. В реальных сценариях вам, вероятно, потребуется завести несколько учетных записей AWS, чтобы разделить трафик устройств для разработки, тестирования и эксплуатации. Что интересно, имейте ввиду, что [Azure IoT Gateway](https://azure.microsoft.com/en-us/documentation/articles/iot-hub-protocol-gateway/) поддерживает конфигурацию нескольких точек подключения, так что один аккаунт Azure может быть использован с разделением точек подключения для разработки, тестирования и эксплуатации.\n- \t🔸**Ограничения:** Ознакомьтесь с [ограничениями](http://docs.aws.amazon.com/iot/latest/developerguide/iot-limits.html), включая размер сообщения устройства, его тип, частоту, количество правил AWS IoT.\n\n### Примеры кода IoT \n\n- \t[Simple Beer Service](https://github.com/awslabs/simplebeerservice) - удивительно полезный пример кода, использующий AWS IoT, Lambda и т.д.\n- \t[IoT-elf](https://github.com/awslabs/aws-iot-elf) - пример на чистом Python, использующий AWS IoT SDK.\n- \t[IoT Button projects](https://www.hackster.io/AmazonWebServices/products/aws-iot-button) на Hackster включает в себя множество различных примеров кода для различных проектов.\n- \t[5 примеров кода IoT](https://github.com/awslabs/aws-iot-examples/): симулятор устройства, образец MQTT, своевременная регистрация, симулятор грузовика, симулятор данных прогноза.\n- \t[Простой пример голоса AWS Alexa](https://developer.amazon.com/public/community/post/TxDJWS16KUPVKO/New-Alexa-Skills-Kit-Template:-Build-a-Trivia-Skill-in-under-an-Hour) является быстрым стартом в использовании голосовых возможностей Alexa и Lambda.\n- \tНекоторые примеры на Raspberry Pi включают в себя [Beacon project](https://github.com/araobp/beacon/blob/master/README.md), [Danbo](https://libraries.io/github/awslabs/aws-iot-demo-for-danbo), и [GoPiGo](https://github.com/awslabs/aws-iotbot).\n\nSES\n---\n\n### Основы SES\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/ses/) ∙ [Документация](https://aws.amazon.com/documentation/ses/) ∙ [ЧаВо](https://aws.amazon.com/ses/faqs/) ∙ [Расценки](https://aws.amazon.com/ses/pricing/)\n-\t**SES** (или простой сервис электронной почты (Simple Email Service)) - это сервис, который открывает выходные точки SMTP для прямой интеграции с вашим приложением.\n\n### Советы по SES\n\n-\t🔹**Обработка отказов:** Убедитесь, что вы решаете эту проблему по мере возникновения. Возможность отправки писем может быть отключена, если SES увидит [большое количество отказов](http://docs.aws.amazon.com/ses/latest/DeveloperGuide/best-practices-bounces-complaints.html).\n-\t🔹**Учетные данные:** Многие разработчики путаются между [учетными данными SES](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/using-credentials.html) и ключами AWS API. Убедитесь, что ввели [учетные данные SMTP](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html), когда используете API SMTP.\n\n### Ошибки и ограничения, связанные с SES\n\n-\t🔸**Доступ в интернет:** Выходные точки SMTP SES находятся в сети Интернет и не будут доступны из места, где интернет недоступен (например, в частной подсети без маршрута на шлюз NAT в таблице маршрутизации). В этом случае, установите инстанс и разверните на нем SMTP релей в подсети с доступом в интернет, а также настройте ваше приложения для отправки почтовых сообщений через этот инстанс, а не через SES. На релее должно быть настроено [правило перенаправления, для отправки всех почтовых сообщений в SES](http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-smtp-existing-server.html)). ❗Если вы используете прокси сервер вместо NAT, убедитесь, что прокси поддерживает SMTP.\n\nМенеджер Сертификатов(Certificate Manager)\n-------------------\n\n### Основы менеджера сертификатов\n\n- 📒 [Домашняя страница](https://aws.amazon.com/certificate-manager/) ∙ [Руководство пользователя](http://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) ∙ [ЧаВо](https://aws.amazon.com/certificate-manager/faqs/) ∙ [Расценки](https://aws.amazon.com/certificate-manager/pricing/)\n- Используйте **Менеджер Сертификатов** чтобы управлять сертификатами SSL/TLS в других сервисах AWS.\n- Поддерживается импорт существующих сертификатов, также как выпуск новых.\n Предоставляет доменные валидированные (DV) сертификаты. [Валидация](http://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate.html) может быть выполнена двумя путями. Первый (и рекомендованный) способ - [через DNS](https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-dns.html). Если зона находится в Route 53 и у пользователя есть доступ, необходимая запись может быть добавлена в консоли в один клик в процессе запроса сертификата. Если зона не находится в Route 53 пользователь должен обновить DNS вручную. Также существует до сих пор предпочитаемый второй способ, который требует больше взаимодействия с пользователем, и происходит путем отсылки электронного почтового сообщения по трем контактным адресам, указанным в регистрационных данных домена в WHOIS и пяти стандартным адресам в домене, для каждого доменного имени, присутствующего в запросе.\n- Менеджер Сертификатов Amazon будет пытаться автоматически [обновить](http://docs.aws.amazon.com/acm/latest/userguide/how-domain-validation-works.html) сертификат, выпущенный Amazon. Для начала он попытается соединиться с доменом по протоколу HTTPS и проверит, что сертификат используемый доменом, является тем же, который он пытается обновить. В случае неудачи, он проверит DNS запись, ранее использованную для валидации. В случае неудачи, Менеджер Сертификатов Amazon попытается провести ручную валидацию, отправив письма на электронные адреса всех доменов в сертификате.\n\n### Альтернативы Менеджеру Сертификатов и привязки\n\n- ⛓Сертификаты выпущенные Менеджером Сертификатов не могут быть использованы где либо, кроме сервисов, которые их поддерживают. Импортированные сертификаты, как бы там ни было, можно использовать где-угодно.\n\n### Советы по Менеджеру сертификатов\n\n- 🔹**Поддерживаемые сервисы:** Управляемые [Балансировщики Нагрузки](#балансировщики-нагрузкиload-balancers), [CloudFront](#cloudfront), [API Gateway](#api-gateway) и [Elastic Beanstalk](https://aws.amazon.com/elasticbeanstalk/).\n- 🔸Во время процесса валидации домена, если валидация по DNS была неудачна, Менеджер Сертификатов отправит электронное письмо каждому контактному адресу, указанному в регистрационных данных домена в WHOIS и до пяти административным адресатам. Некоторые анти-спам фильтры могут пометить  такие письма как спам. Вам стоит проверить папку спам в своем почтовом ящике, если вы не получили письмо с подтверждением.\n- 🔹 Хотите установить сертификат на тестовый домен, на котором нет почты? Используйте DNS валидацию вместо этого.\n- 🔹Запомните, когда вы заказываете сертификат для вайлдкард(то есть любое значение для суб-доменов) домена, сертификат не будет работать для всех уровней ниже звездочки. Для примера одобрен и выпущен сертификат для `*.bar.example.com`. Он будет работать для `foo.bar.example.com`, но не `bar.example.com`. Также, скорее всего он не будет работать для `www.bar.foo.example.com`. Вам потребуется добавить каждый из этих доменов в запрос на создание сертификата.\n\n### Ошибки и ограничения, связанные с Менеджером сертификатов\n\n- 🔸Если вы хотите использовать **Менеджер Сертификатов** для CloudFront CDN, сертификат должен быть выпущен или импортирован в регионе us-east-1 (Северная Вирджиния).\n- 🔸Сертификаты используемые с Эластичными Балансировщиками Нагрузки должны быть выпущены в том же регионе, что и балансировщик нагрузки. Сертификаты нельзя перемещать или копировать между регионами, по состоянию на июль 2017 года. Если домен использует балансировщики нагрузки в разных регионах - разные сертификаты должны быть запрошены для каждого региона.\n- 🔸**IoT** имеет [свой способ](http://docs.aws.amazon.com/iot/latest/developerguide/create-device-certificate.html) установки сертификатов.\n- 🔸По умолчанию, макисимальное количество доменов в сертификате - 10. Вы можете увеличить этот лимит максимум до 100 путем обращения в поддержку AWS. **Имейте ввиду** для каждого домена включенного в запрос на сертификат, вы должны нажать 'принять' в сообщении присланном на адрес в этом домене. Например вы запросили сертификат с 42 разными доменами и субдоменами, вам придется нажать 'принять' 42 раза по разным ссылкам.\n\t- 🔹Если вы запросите увеличение лимита у службы поддержки AWS, они ответят на ваш запрос с просьбой подтвердить. Вы можете обойти это, написав в теле вашего первоначального запроса:\n```\"I acknowledge at the moment, there is no method to add or remove a name from a certificate. Instead, you must request a new certificate with the revised namelist and you must then re-approve all of the names in the certificate, even if they'd been previously approved.\"```\n- 🔸Нет никакой возможности на текущий момент добавить или удалить домен из существующего сертификата. Вы должны запросить новый сертификат и заново подтвердить для каждого из запрошенных доменов. \n\nWAF\n-------------------\n\n### Основы WAF\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/waf/) ∙ [Документация](https://aws.amazon.com/documentation/waf/) ∙ [ЧаВо](https://aws.amazon.com/waf/faq/) ∙ [Расценки](https://aws.amazon.com/waf/pricing)\n- WAF (Брандмауэр для интернет‑приложений) используется совместно со службами CloudFront и ALB для проверки и блокировки / разрешения веб-запросов на основе настраиваемых пользователем условий.\n- HTTPS и HTTP запросы поддерживаются этим сервисом.\n- Сила WAF заключается в обнаружении злонамеренных действий на основе сопоставления с шаблоном для таких атак, как инъекции SQL, XSS и т.д.\n- WAF поддерживает проверку запросов [полученных как через IPv6, так и через IPv4](https://aws.amazon.com/about-aws/whats-new/2016/10/ipv6-support-for-cloudfront-waf-and-s3-transfer-acceleration/).\n\n### Советы по WAF\n\n- Получение истории вызовов API WAF может быть произведено через CloudTrail. Включить можно в консоли CloudTrail.\n- Также возможно получение [полных логов проверки всех веб запросов](https://aws.amazon.com/about-aws/whats-new/2018/08/aws-waf-launches-new-comprehensive-logging-functionality/)\n\n### Ошибки и ограничения, связанные с WAF\n\n- По состоянию на май 2019 года, AWS WAF доступен в  Amazon CloudFront и 12 коммерческих регионах AWS : US East (N. Virginia), US East (Ohio), US West (Oregon), US West (N. California), EU (Ireland), EU (Frankfurt), EU (London), EU (Stockholm), Asia Pacific (Tokyo), Asia Pacific (Sydney), Asia Pacific (Singapore), и Asia Pacific (Seoul).\n\n\nOpsWorks\n-------------------\n\n### Основы OpsWorks\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/opsworks/) ∙ [Документация](https://aws.amazon.com/documentation/opsworks/) ∙ [ЧаВо](https://aws.amazon.com/opsworks/faqs/) ∙ Расценки: [Stacks](https://aws.amazon.com/opsworks/stacks/pricing/), [Chef Automate](https://aws.amazon.com/opsworks/chefautomate/pricing/), [Puppet Enterprise](https://aws.amazon.com/opsworks/puppetenterprise/pricing/)\n- OpsWorks - это сервис управления конфигурацией, который использует [Chef](https://www.chef.io/chef/) или [Puppet](https://www.puppet.com). Он разделен на три различных сервиса:\n  - [OpsWorks Stacks](https://aws.amazon.com/opsworks/stacks/): Служба позволяет настраивать и запускать стеки, соответствующие потребностям вашего приложения, и позволяет автоматизировать развертывание приложений. Запуск Chef может быть выполнен вручную командой Execute Cookbooks, в ином случае, кукбуки выполняются только как часть событий жизненного цикла..\n    - Стеки OpsWorks отличаются от стандартных служб управления конфигурациями тем, что они также позволяют выполнять некоторую автоматизацию инфраструктуры и приложений (например, создание инстансов Amazon EC2 и развертывание приложений через кукбуки Chef).\n  - [OpsWorks for Chef Automate](https://aws.amazon.com/opsworks/chefautomate/): Эта служба запускает выделенный сервер Chef Automate в вашем аккаунте, который можно использовать для подключения нод, загрузки кукбуков и настройки систем. Автоматический патчинг, резервное копирование, обновления ОС и минорные обновления версий Chef предоставляются как часть службы. Существует API AWS для подключения/отключения нод. Запуск Chef может быть запланирован на нодах путем использования [chef-client cookbook](https://supermarket.chef.io/cookbooks/chef-client).\n  - [OpsWorks for Puppet Enterprise](https://aws.amazon.com/opsworks/puppetenterprise/): Эта служба запускает выделенный сервер Puppet Master в вашем аккаунте, который можно использовать для подключения нод, загрузки модулей и настройки систем. AАвтоматический патчинг, резервное копирование, обновления ОС и минорные обновления версий Puppet предоставляются как часть службы. Существует API AWS для подключения/отключения нод. По умолчанию, агент Puppet запускается на подключенных нода автоматически каждые 30 минут.\n- OpsWorks для Chef Automate и OpsWorks для Puppet Enterprise предназначен исключительно для управления конфигурацией и не предоставляет инфраструктуру кроме Chef Server/Puppet Master, которые создаются в нашей учетной записи.\n- Все три сервиса OpsWorks поддерживают управление как Amazon EC2 так и локальной инфраструктуры, в любом случае отдельные моменты реализации слегка различаются.\n  - OpsWorks Stacks позволяет вам регистрировать инстансы и устанавливать агент OpsWorks Agent для присоединения к стэку.\n  - OpsWorks для Chef Automate и OpsWorks для Puppet Enterprise позволяет вам подключать новую или существующую инфраструктуру используя либо API opsworks-cm:AssociateNode либо поддерживаемый поставщиком метод для подключения нод к Chef Server или Puppet Enterprise.\n- Хотя OpsWorks позволяет вам работать с обычными рецептами Chef и модулями Puppet во время создания стэка, создание собственных рецептов потребует знаний синтакса Chef или Puppet. Код Chef/Puppet не поддерживается поддержкой AWS.\n- По состоянию на декабрь 2016 года, OpsWorks Stacks поддерживает Chef версий [12, 11.10.4, 11.4.4 and 0.9.15.5](http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook.html).\n- По состоянию на декабрь 2016 года, OpsWorks для Chef Automate использует [Chef Server версии 12.11.1](http://docs.aws.amazon.com/opsworks/latest/userguide/welcome_opscm.html) Это текущая стабильная Chef.\n- [Berkshelf](http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-chef11-10.html#workingcookbook-chef11-10-berkshelf) может быть использован со стэками Chef версии 11.10 или более поздней для управления кукбуками и их соответствующими зависимостями. В любом случае, в стэках Chef 12.x, Berkshelf должен быть установлен администратором стэка.\n- Запуск вашей собственной среды Chef может быть определенной альтернативой для рассмотрения - некоторые соображения перечислены [в этой статье Bitlancer.](http://www.bitlancer.com/blog/2015/10/05/opsworks-vs-chef.html)\n\n### Альтернативы OpsWorks и привязки\n\n- Основные конкуренты в управлении конфигурациями включают:\n  - [Chef](https://chef.io)\n  - [Puppet](https://puppet.com)\n  - [Ansible](https://www.ansible.com).\n\n### Советы по OpsWorks\n\n- OpsWorks Stacks и OpsWorks для Chef Automate используют кукбуки Chef для конфигурации. Chef предоставляет бесплатные тренинги для обучения синтаксису, лучшим практикам и т.д. на [https://learn.chef.io](https://learn.chef.io).\n- OpsWorks для Puppet Enterprise использует манифесты Puppet для конфигурации. Puppet предоставляет очень полезную виртуальную машину, которую можно скачать на [https://learn.puppet.com/](https://learn.puppet.com/).\n\n### Ошибки и ограничения, связанные с OpsWorks\n\n- OpsWorks Stacks не доступен в следующих регионах:\n  - Montreal\n  - GovCloud\n  - Beijing\n- OpsWorks для Chef Automate и OpsWorks для Puppet Enterprise недоступны в следующих регионах:\n  - Montreal\n  - Sao Paulo\n  - GovCloud\n  - London\n  - Paris\n  - Seoul\n  - Mumbai\n\nBatch\n-------------------\n\n### Основы Batch\n\n-\t📒 [Домашняя страница](https://aws.amazon.com/batch/) ∙ [Документация](https://aws.amazon.com/documentation/batch/) ∙ [ЧаВо](https://aws.amazon.com/batch/faqs/) ∙ [Расценки](https://aws.amazon.com/batch/pricing/)\n- **AWS Batch** - сервис, предлагающий среду для выполнения пакетных вычислительных задач. Сервис динамически предоставляет оптимальное количество вычислительных ресурсов необходимых задачам на основе хи требованиям к ресурсам и может масштабироваться на сотни и тысячи [задач](http://docs.aws.amazon.com/batch/latest/userguide/jobs.html).\n- Эти пакетные рабочие нагрузки имеют доступ ко всем другим сервисам и функциям AWS.\n- AWS Batch, вместе со [спотовыми инстансами](https://aws.amazon.com/blogs/compute/cost-effective-batch-processing-with-amazon-ec2-spot/) может выполнять задачи, когда необходимые вычислительные мощности доступны, таким образом предоставляяя оптимальную загрузку вычислительных ресурсов.\n- Пакетные нагрузки оборачиваются в [образ Docker](https://www.docker.com/). Эти образы вносятся в репозиторий [EC2 Container Registry](https://aws.amazon.com/ecr/) (ECR), или любой частный репозиторий, который может быть доступен с AWS.\n-[Описание задачи(Job Definition)](http://docs.aws.amazon.com/batch/latest/userguide/job_definitions.html) включает в себя адрес образа Docker с рабочей нагрузкой, а также позволяет пользователям указать конкретные детали среды, такие как количество виртуальных процессоров, памяти, подключаемые тома, переменные окружения, параметры, стратегию повторов, свойства контейнера, а также IAM роль.\n-[Вычислительные окружения](http://docs.aws.amazon.com/batch/latest/userguide/compute_environments.html) это кластера EC2, которые предоставляют вычислительную среду, для запуска пакетных рабочих нагрузок.\n- AWS Batch предоставляет как управляемые, так и неуправляемые вычислительные окружения. Управляемые окружения разворачиваются и управляются AWS, в то время, как неуправляемые окружения управляются клиентами.\n- Описания задач вносятся в [Очередь Задач(Job Queue(s))](http://docs.aws.amazon.com/batch/latest/userguide/job_queues.html) для запуска. Каждая очередь имеет приоритет, и, как минимум, одно вычислительное окружение, сопряженное с ней.\n- AWS Batch использует [ECS](https://aws.amazon.com/ecs/) для запуска контейнеризированных задач.\n\n### Советы по Batch\n\n- AWS Batch поддерживает приоретизацию задач через приоритет очереди задач(Job Queue Priority). Чем выше номер - тем выше приоритет.\n- AWS Batch поддерживает запуск вычислительного окружения в конкретном VPC и подсети.\n- Вычислительное окружение - это то же самое, что и [ECS Кластер](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_clusters.html).\n- AWS Batch дополнительно не оплачивается. Вы платите только за сервисы AWS, которые используются - такие как инстансы EC2 и любые другие ресурсы, потребляющиеся при выполнении пакетного задания.\n- Свяжите [Роли и политики IAM](http://docs.aws.amazon.com/batch/latest/userguide/IAM_policies.html) с вычислительным окружением, чтобы предоставить контейнерам доступ к другим ресурсам AWS.\n- 🔹 Используйте неуправляемые вычислительные окружения, если вам нужны специализированные ресурсы, такие как выделенные хосты или [EFS](https://aws.amazon.com/efs/).\n\nSQS\n-------------------\n\n### Основы SQS\n\n- 📒  [Домашняя страница](https://aws.amazon.com/sqs/) ∙ [Документация](https://aws.amazon.com/documentation/sqs/) ∙ [ЧаВо](https://aws.amazon.com/sqs/faqs/) ∙ [Расценки](https://aws.amazon.com/sqs/pricing/)\n- SQS - это высокомасштабируемая, полностью управляемая служба очереди сообщений от AWS.\n- SQS поддерживает модель извлечения, когда источники передают сообщения в *очередь*, а потребители извлекают сообщения из очереди.\n- SQS предоставляет тайм-аут видимости сообщения, в течение которого обрабатываемое сообщение не будет доставлено другим потребителям. Если потребитель не удаляет сообщение после обработки, оно становится доступным для других потребителей по истечении времени ожидания видимости сообщения. Этот параметр называется VisibilityTimeout.\n- Каждое сообщение может иметь до 10 пользовательских полей или атрибутов.\n- SQS позволяет источникам устанавливать задержку до 15 минут, прежде чем сообщения будут доставлены потребителям. Этот параметр называется DelaySeconds.\n- Существует два типа очередей, которые поддерживает SQS -\n    - Стандартные очереди(Standard Queues)\n        - Гарантирует **как минимум одну** доставку сообщеинй.\n        - Не сохраняет порядок очереди доставки сообщений.\n    - Очередь типа первый пришел, первый ушел(FIFO Queues)\n        - Гарантирует **только одну** доставку сообщения\n        - Гарантирует сохранность порядка доставки сообщений\n- SQS поддерживает гранулярный доступ к вызовам различных API и очередям через политики IAM.\n- Сообщения, которые не обрабатываются, могут быть помещены в очередь недоставленных сообщений.\n\n### Альтернативы SQS и привязки\n\n- Альтернативы SQS включают [Kafka](https://kafka.apache.org/), [RabbitMQ](https://www.rabbitmq.com/), [ActiveMQ](http://activemq.apache.org/) и другие.\n- В Google Cloud Platform есть Pub/Sub, а в  Azure есть Azure Queue Service.\n- [SQS vs SNS](#альтернативы-sns-и-привязки)\n\n### Советы по SQS\n\n- SNS может быть использован совместно с SQS для построения механизма “fan out”, путем подписки очереди SQS на тему SNS.\n- SQS поддерживает шифрование посредством AWS KMS.\n- Тревоги Cloudwatch могут быть созданы путем использования [различных метрик SQS](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/sqs-metricscollected.html) для запуска автоматического масштабирования и/или отправки оповещений.\n\n### Ошибки и ограничения, связанные с SQS\n\n- 🔸 SQS не имеет конечной точки в VPC (в отличии от S3 и DynamoDB), таким образом доступ к SQS происходит через общедоступные выходные точки API SQS.\n- 🔸 Очереди FIFO(Первый пришел, первый ушел) ограничены частотой вызовов в 300 вызовов API в секунду.\n- 🔸 Очереди FIFO не могут быть подписаны на тему SNS.\n- 🔸 Стандартные очереди могут доставлять дубликаты сообщений независимо от окна видимости. Если ваш выбор - единовременная доставка, используйте очереди FIFO или создайте дополнительную прослойку для устранения дубликатов.\n- 🔸 Вы можете отправлять/получать сообщения пакетами, однако в пакете может быть не более 10 сообщений.\n\n\nSNS\n---------------------\n\n### Основы SNS\n\n- 📒  [Домашняя страница](https://aws.amazon.com/sns/) ∙ [Документация](https://aws.amazon.com/documentation/sns/) ∙ [ЧаВо](https://aws.amazon.com/sns/faqs/) ∙ [Расценки](https://aws.amazon.com/sns/pricing/)\n- **SNS** (Простой сервис уведомлений(Simple Notification Service)) - это высоко-масштабируемый полностью управляемый сервис сообщений на базе публикаций/подписок, который также может быть использован для мобильных уведомлений.\n- SNS может передавать сообщения подписчикам посредством транспортных протоколов [SMS](http://docs.aws.amazon.com/sns/latest/dg/SMSMessages.html), [Email](http://docs.aws.amazon.com/sns/latest/dg/SubscribeTopic.html), [SQS](http://docs.aws.amazon.com/sns/latest/dg/SendMessageToSQS.html), и [HTTP/S](http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html).\n- Источники сообщений публикуют их в Темы SNS(SNS Topics), в которых может быть много подписчиков.\n- Каждая подписка имеет соответствующий [протокол](http://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html), который используется для оповещения подписчика.\n- Копия сообщения направляется каждому подписчику посредством соотвествующего протокола.\n- SNS также может [вызывать функции lambda](http://docs.aws.amazon.com/sns/latest/dg/sns-lambda.html).\n\n### Альтернативы SNS и привязки\n\n- Популярными альтернативами SNS являются [Kafka](https://kafka.apache.org/), [Notification Hubs](https://azure.microsoft.com/en-us/services/notification-hubs/) в Azure, и [Pub/Sub](https://cloud.google.com/pubsub/docs/overview) в Google Cloud.\n- **SNS и SQS:**\n    - SNS и SQS оба являются высокомасштабируемыми, полностью управляемыми сервисами сообщений предоставляемыми AWS.\n    - SQS поддерживает модель *Вытаскивания данных(pull)*, в то время, как SNS поддерживает модель *Отправки данных(push)*. Потребители должны запрашивать данные из очереди SQS, в то время, как им приходят сообщения с Темы SNS.\n    - Сообщение SQS предназначено для обработки только одним подписчиком, в то время, как Темы SNS имеют множество подписчиков.\n    - После обработки, сообщение SQS удаляется из очереди, для того, чтобы избежать повторной обработки.\n    - Сообщение SNS *направляется* всем подписчикам темы одновременно и это делает невозможным удаление сообщения из Темы.\n    - SNS поддерживает массу транспортных протоколов доставки сообщений подписчикам, в то время, как подписчики SQS могут запрашивать сообщения из очереди только через HTTPS.\n\n### Советы по SNS\n\n- Архитектура [Fan-out](http://docs.aws.amazon.com/sns/latest/dg/SNS_Scenarios.html) может быть достигнута путем назначения нескольких подписчиков на тему. Это особенно полезно, когда события должны распространяться на несколько изолированных систем.\n- Темы SNS могут быть использованы для передачи [вебхуков](https://en.wikipedia.org/wiki/Webhook) с [поддержкой откладывания](http://docs.aws.amazon.com/sns/latest/dg/DeliveryPolicies.html) подписчикам через HTTP/S.\n- [Очереди SQS](http://docs.aws.amazon.com/sns/latest/dg/SendMessageToSQS.html) могут быть подписаны на темы SNS.\n- SNS используется для управления уведомлениями для других сервисов AWS, таких как уведомления [групп автоматического масштабирования(Autoscaling Groups)](http://docs.aws.amazon.com/autoscaling/latest/userguide/ASGettingNotifications.html)' , [Тревоги CloudWatch](http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/US_SetupSNS.html), и т.д.\n- SNS часто используется, как “клей” между несопоставимыми системами, такими, как GitHub и сервисы AWS.\n\n### Ошибки и ограничения, связанные с SNS\n\n- 🔸 Подписчики SNS подключающиеся по HTTP/S должны иметь доступ к общедоступным выходным точкам, так как SNS не поддерживает частные выходные точки (типа тех, которые находятся в частных подсетях внутри VPC).\n- 📜 В сценарии fan-out [SQS с включенным шифрованием на стороне сервера(SSE-enabled SQS)](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html) подписанные на тему SNS [не получат](https://lobster1234.github.io/2017/10/14/fan-out-with-sns-and-sqs-gotcha/) сообщений, посланных в тему.\n\nВысокая доступность\n-----------------\n\nЭтот раздел охватывает советы и информацию по достижению [высокой доступности](https://en.wikipedia.org/wiki/High_availability).\n\n\n\n### Советы по высокой доступности\n\n-\tAWS предлагает два уровня отказоустойчивости, [регионы и зоны доступности (AZs)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-regions-availability-zones).\n-\tПри правильном использовании регионы и зоны обеспечивают высокую доступность. Возможно, вы захотите использовать других провайдеров для еще более значительного снижения бизнес-рисков (то есть не привязывать свою компанию к одному поставщику), но надежность AWS в различных регионах крайне высока.\n-\t**Несколько регионов:** Использование нескольких регионов является сложным, поскольку по сути это похоже на управление совершенно отдельными инфраструктурами. Это необходимо для критически важных для бизнеса услуг с высоким уровнем резервирования. Однако для многих приложений (например, для вашего стартапа ориентирующегося на средний класс потребителей) развертывание обширной избыточности по регионам может оказаться излишним.\n-\tЭтот блог [High Scalability](http://highscalability.com/blog/2016/1/11/a-beginners-guide-to-scaling-to-11-million-users-on-amazons.html) является хорошим руководством, призванным помочь вам понять, нужно ли вам растягивать ваше приложение на несколько регионов.\n-\t🔹**Несколько зон доступности(AZ):** Разумное использование AZ - первый инструмент в обеспечении высокой доступности!\n\t-\tТипичной архитектурой высокой доступности для одного региона является развертывание в двух или более зонах доступности с балансировкой нагрузки, как на [этом изображении от AWS](http://media.amazonwebservices.com/architecturecenter/AWS_ac_ra_ftha_04.pdf).\n\t-\tБольшая часть простоев в сервисах AWS затрагивает только одну зону. Однако в истории были редкие перебои, затрагивающие несколько зон одновременно (например, [великий отказ EBS 2011 года](http://aws.amazon.com/message/65648/)), но, как правило, перебои в работе большинства клиентов связаны с использованием только одной зоны доступности в определенных вариантах развертывания инфраструктуры.\n\t-\tСледовательно, проектируйте свою архитектуру так, чтобы минимизировать влияние отказов в зонах доступности, особенно отказов в одной зоне.\n\t-\tРазворачивайте ключевую инфраструктуру, как минимум, в двух или трех зонах доступности . Репликация одного ресурса в более чем трех зонах часто не имеет смысла, если у вас есть другие механизмы резервного копирования, такие как снапшоты в S3.\n\t-\tИспользование второй или третьей зоны доступности должно значительно улучшить доступность, но дополнительная надежность из-за использования четырех или более зон доступности, может не оправдать затраты или сложность инфраструктуры (кроме случаев, если у вас нет других причин, таких как емкость или рыночные цены на спот инстансы).\n\t-\t💸Помните о **затратах на передачу данных между зонами доступности**. Это может стать неприятным сюрпризом в архитектурах с большими объемами передачи траффика между границами зон доступности.\n\t-\tРаспределяйте инстансы равномерно по всем доступным зонам доступности, так что в случае отказа зоны доступности вы потеряете только минимальную часть вашей общей емкости.\n\t-\tЕсли ваша архитектура содержит точки отказа, поместите их все в одну зону доступности. Это может выглядеть нелогичным, но это уменьшает вероятность падения инфраструктуры изза выхода из строя одной зоны доступности.\n-\t**EBS и хранилище на инстансе:** В течении долгих лет, у EBS был худший показатель доступности, нежели у хранилища на инстансе. Для систем, где индивидуальные инстансы могли быть уничтожены и перезапущены легко и быстро, хранилища на инстансах с достаточной отказоустойчивостью, показывали более высокий уровень доступности. Однако, с тех пор, EBS был значительно улучшен, и современные типы инстансов (с 2015 года) идут только с поддержкой EBS, так что этот подход, хотя и был в свое вермя полезен, на сегодня сильно устарел.\n-\tУбедитесь, что вы правильно [понимаете и используете CLB/ALB](#балансировщики-нагрузкиload-balancers). Многие отказы были вызваны из-за не использования балансировщиков нагрузки или неправильного понимания их работы и, следовательно, неправильной настройке.\n\n### Ошибки и ограничения, связанные с высокой доступностью\n\n-\t🔸**Наименование зон доступности** различается от одного пользовательского аккаунта к другому. Ваша зона “us-west-1a” не та же самая, как зона “us-west-1a” у другого клиента — буквы назначаются физической зоне доступности произвольно для каждого аккаунта. Это может привести к ошибкам, если вы используете различные аккаунты AWS. Имейте ввиду, что ID зоны доступности остаются одинаковыми во всех аккаунтах и это может быть использовано для надежного ориентирования при работе между разными аккаунтами AWS.\n-\t🔸💸**Траффик между зонами доступности** не бесплатен. В больших масштабах, это может добавить серьезный объем затрат. Если возможно, оптимизируйте передачу данных так, чтобы трафик циркулировал в пределах одной зоны доступности настолько, насколько это возможно.\n\nПлатежи и управление расходами\n---------------------------\n\n### Прозрачность расходов и выставления счетов\n\n-\tAWS предлагает [**бесплатный уровень**](https://aws.amazon.com/free/) услуг, который позволяет очень ограниченное использование ресурсов без оплаты. Например, микро инстанс и небольшой объем хранилища бесплатно. Многие сервисы доступны на бесплатном уровне только в течении 12 месяцев с момента регистрации аккаунта, однако другие сервисы предлагают бесплатное использование на неопределенный срок. (Если у вас есть старый аккаунт, но вы начинаете новый проект, зарегистрируйте новый аккаунт, чтобы получить право на бесплатный уровень.) [AWS Activate](https://aws.amazon.com/activate/) расширяет этот уровень до десятков тысяч долларов бесплатных кредитов для стартапов в [определенных фондах или акселераторах](https://aws.amazon.com/activate/portfolio-detail/).\n-\tВы можете установить [**уведомления о расходах**](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/free-tier-alarms.html), чтобы быть оповещенным о неожиданных затратах, таких как затраты, превышающие бесплатный уровень. Вы можете настроить их [гранулярно](https://wblinks.com/notes/aws-tips-i-wish-id-known-before-i-started/#billing).\n-\tAWS предлагает [Обозреватель затрат(Cost Explorer)](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-explorer-what-is.html) - инструмент для обеспечения прозрачности затрат.\n-\tК сожалению, консоли AWS и инструментов для выставления счетов не всегда достаточно, чтобы обеспечить хороший обзор затрат. Для больших учетных записей консоль биллинга AWS может быть тормозить или падать из-за таймаута.\n-\t**Инструменты:**\n\t-\t🔹Включите [отчеты о затратах(billing reports)](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/detailed-billing-reports.html) и установите инструмент с открытым исходным кодом, для помощи в управлении и контроле использование ресурсов AWS. [**Teevity Ice**](https://github.com/Teevity/ice) (созданный в Netflix) - возможно то, что вам следует попробовать в первую очередь. Можно попробовать [docker-ice](https://github.com/jonbrouse/docker-ice) - докеризированную версию, которая облегчает установку.\n\t-\t🔸Одна из проблем с Ice заключается в том, что он не покрывает амортизированную стоимость зарезервированных инстансов.\n\t-\tДругие инструменты включают [Security Monkey](https://github.com/Netflix/security_monkey) и [Cloud Custodian](https://github.com/capitalone/cloud-custodian).\n\t-\tИспользуйте [Простой ежемесячный калькулятор AWS(AWS Simple Monthly Calculator)](https://calculator.s3.amazonaws.com/index.html), чтобы получить оценку стоимости использования услуг AWS на основе определенной информации, которую вы предоставляете. Ежемесячные платежи будут зависеть от фактического использования вами сервисов AWS и могут отличаться от оценок, предоставленных калькулятором.\n-\t**Сторонние сервисы:** Некоторые компании предлагают услуги, разработанные, чтобы помочь вам получить представление о расходах или снизить расходы на оплату услуг AWS, например [Cloudability](https://www.cloudability.com/), [CloudHealth Technologies](https://www.cloudhealthtech.com/), и [ParkMyCloud](http://www.parkmycloud.com/). Некоторые из них взимают оплату в размере процента вашего счета, что может быть дорого. Ознакомьтесь с [рыночным ландшафтом](#инструменты-и-услуги-представленные-на-рынке).\n-\tДоверенный советник AWS ([AWS Trusted Advisor])(https://aws.amazon.com/premiumsupport/trustedadvisor/) - является еще одним сервисом, который может помочь разобраться с проблемой затрат.\n-\tНе стесняйтесь спрашивать у своего менеджера аккаунта рекомендации по уменьшению ваших затрат. Это их работа, чтобы вы были довольны использованием AWS.\n-\t**Тэгирование для прозрачности затрат:** По мере роста инфраструктуры ключевой частью управления расходами является понимание того, где они лежат. Крайне рекомендуется [тэгировать ресурсы](https://aws.amazon.com/blogs/aws/resource-groups-and-tagging/), и по мере роста сложности инфраструктуры, эффективно группировать их. Если вы [правильно настроите распределение счетов](http://aws.amazon.com/blogs/aws/aws-cost-allocation/), вы сможете получить прозрачность затрат исходя из огранизации, продукта, отдельного инженера или любым другим удобным вам путем.\n-\tЕсли вам необходимо произвести свой анализ сырых платежных данных или вам надо передать их в сторонний сервис анализа затрат, [включите](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/detailed-billing-reports.html#turnonreports) функцию [детализированного платежного отчета(detailed billing report)](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/detailed-billing-reports.html#detailed-billing-report).\n-\tНесколько учетных записей Amazon могут быть связаны в платежных целях используя функцию [Консолидированное выставление счетов(Consolidated Billing)](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/consolidated-billing.html). Крупные предприятия могут иметь сложную бухгалтерскую структуру, в зависимости от владения и процессов одобрения.\n-\tНесколько учетных записей Amazon могут управляться централизовано посредством [AWS Organizations](https://aws.amazon.com/organizations/).\n\n### Затраты на передачу данных в AWS\n\n-\tДля развертываний, в которых используется значительный сетевой трафик, значительная часть затрат AWS приходится на передачу данных. Кроме того, стоимость передачи данных в пределах зоны доступности, внутри регионов, между регионами, а также из AWS в Интернет и обратно значительно варьируется в зависимости от выбора варианта развертывания.\n-\tНекоторые из наиболее распространенных ошибкок:\n\t-\t🔸*Траффик между зонами доступности:* Имейте ввиду, что траффик EC2 между зонами доступности, по факту такой же, как и между регионами. Например, развертывание кластера Cassandra в нескольких зонах доступности может быть полезно для обеспечения [высокой доступности](#высокая-доступность), но может нанести ущерб, за счет затрат на передачу данных.\n\t-\t🔸*Использование публичных IP-адресов без необходимости:* Если вы используете Elastic IP или общедоступный IP-адрес инстанса EC2, вы будете нести дополнительные расходы, даже если к нему обращаются локально в пределах AZ.\n\t-\t🔸*Обработка данных управляемым шлюзом NAT:* Управляемы шлюзы NAT используются чтобы пропускать траффик из приватных подсетей по цене 4.5¢ в виде платежа за обработку данных поверх стоимости передачи данных. После определенного момента, запуск NAT на своих инстансах становится более экономически выгодным.\n\t-\t🔸*Некоторые сервисы не тарифицируют передачу данных между зонами доступности:* Многие сервисы AWS, которые вы по существу не рассматриваете, предлагают скрытую ценность по причине бесплатной передачи данных между зонами доступности. EFS, RDS, MSK и другие - выступают примером этого.\n-\tЭто изображение дает обзор:\n\n![Затраты на передачу данных в AWS](../figures/aws-data-transfer-costs.png)\n\n### Управление затратами на EC2\n\n-\tВ EC2 существует компромисс между инженерными усилиями (больше анализа, больше инструментов, более сложные архитектуры) и расходами на AWS. Если ваши затраты на EC2 малы, эти усилия обычно не обходятся дороже того инженерного времени, которое потребуется для того, чтобы сделать так, чтобы все работало. Однако, если расходы начнут превышать заработную плату инженера, могут потребоваться серьезные инвестиции.\n-\tБолее крупные инстансы не обязательно имеют более высокую цену на спотовом рынке, поэтому вам следует рассмотреть доступные варианты и определить, какие инстансы будут наиболее экономически эффективными для ваших работ. Изучите [Советника по ставкам(Bid Advisor)](https://aws.amazon.com/ec2/spot/bid-advisor/).\n-\t🔹**Спотовые инстансы:**\n\t-\t[Спотовые инстансы EC2](https://aws.amazon.com/ec2/spot/) - это способ получить ресурсы EC2 со значительной скидкой - часто на порядок дешевле, чем стандартные цены на ресурсы по требованию - если вас устраивает возможность того, что они могут быть отключены с малым временем после предупреждения или вообще без предупреждения.\n\t-\tИспользуйте спотовые инстансы для получения весьма серьезных скидок в любых случаях, когда вы используете ресурсы, которые могут быть перезагружены и не нуждаются в поддержке постоянного состояния в течении долгосрочного периода.\n\t-\tОгромная экономия, которую вы можете получить с помощью спотовых инстансов, достигается за счет значительного увеличения сложности при подготовке и определении необходимости доступности вычислительных мощностей.\n\t-\tAmazon поддерживает спотовые цены на колеблющемся уровне, ориентированном на рынок, основываясь на своих запасах неиспользованных мощностей. Цены обычно низкие, но возможны [весьма высокие всплески цен](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-limits.html#spot-bid-limit). Посмотрите [историю цен](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html), чтобы иметь представление об этом.\n\t-\tВы устанавливаете высокую цену предложения, чтобы указать, насколько много вы готовы платить, но платите только по действующей ставке, а не по ставке, которую вы указали. Если рыночная ставка превышает вашу ставку, ваш инстанс будет отключен.\n\t-\tЦены устанавливаются как по инстансам, так и по зонам доступности. Цены на один и тот же тип инстанса могут широко различаться в различных зонах доступности в одно и то же время. Разные типы инстансов могут иметь совершенно разные цены, даже для одновременно запущенных типов инстансов в одной и той же зоне.\n\t-\tСравните цены между типами инстансов в целях заключения наилучшей сделки.\n\t-\tИспользуйте спотовые инстансы всегда, когда это возможно. Установка высокой цены предложения гарантирует, что ваши машины будут работать в подавляющем большинстве случаев за небольшую долю от обычной цены.\n\t-\tВы можете получить уведомление об отключении за две минуты по причине превышения цены предложения путем опроса [метаданных вашего спот инстанса](https://aws.amazon.com/blogs/aws/new-ec2-spot-instance-termination-notices/), а также путем просмотра [событий отключения в CloudWatch](https://aws.amazon.com/about-aws/whats-new/2018/01/amazon-ec2-spot-two-minute-warning-is-now-available-via-amazon-cloudwatch-events/).\n\t-\tУбедитесь, что то, что вы используете, хорошо адаптируется к спотовым инстансам, прежде чем вкладывать значительные средства в инструменты для управления конкретной конфигурацией.\n-\t**Спотовый флот(Spot fleet):**\n\t-\tВы можете добиться еще больших сокращений затрат в то же время, как и улучшения стабильности парка инстансов, по отношению к обычному использованию спортовых инстансов посредством использования [спотового флота(парка инстансов)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet.html) чтобы делать ставки на инстансы среди различных типов инстансов, зон доступности, а также (путем запроса нескольких спотовых флотов) регионов.\n\t-\tИспользование спотовых флотов преследует цель поддержки заданной (и взвешенной по типу инстанса) полной вычислительной емкости в кластере серверов. Если спотовая цена одной комбинации типа инстанса и зоны доступности поднимается выше взвешенной ставки, он будет отключать запущенные инстансы и поднимать новые инстансы другого типа и местоположения, чтобы поддерживать целевую емкость без превышения целевой стоимости кластера.\n-\t**Лучшие практики использования спотовых инстансов:**\n\t-\t**Профилирование приложений:**\n\t\t-\tПрофилируйте ваше приложение, чтобы выяснить его характеристики во время выполнения. Это поможет понять минимальные требования к ресурсам процессора, памяти и диска. Наличие этой информации очень важно, прежде чем пытаться оптимизировать расходы на спотовые ресурсы.\n\t\t-\tКак только вы определите минимальные требования приложения, вы сможете делать ставки на различные варианты типов инстансов, вместо того, чтобы ротировать инстансы одного типа (это дает большие шансы получения спотового инстанса для запуска вашего приложения). Например, если вы знаете, что четырех ядер достаточно для запуска вашей задачи, вы можете выбрать тип инстанса, у которого количество ядер равно или более четырех, а также имеет минимальную цену на спот рынке, исходя из исторических данных. Это поможет вам выставить ставку на инстансы с самой большой скидкой (менее запрашиваемые на текущий момент веремени).\n\t-\t**Мониторинг и прогнозирование цены спот инстансов:**\n\t\t-\tЦены на спот инстансы колеблются в зависимости от типа инстанса, времени суток, региона и зоны доступности. Инструменты, такие как AWS API и AWS CLI позволяют описывать метаданные спотовой цены с указанием времени, типа инстанса, а также региона/зоны доступности.\n\t\t-\tОсновываясь на истории цен спот инстансов, вы могли бы потенциально создать множество алгоритмов, которые помогут вам выбрать тип экземпляра исходя из стратегии **оптимизации расходов**, **максимального повышения доступности** или **обеспечения предсказуемой производительности**.\n\t\t-\tВы также можете отследить количество случаев, когда инстанс определенного типа был забран (из-за превышения ставки), и построить график на доске, чтобы улучшить свой алгоритм в зависимости от времени суток.\n\t-\t**Утилизация ресурсов спотовых машин:**\n\t\t-\tДля выполнения нагрузок с всплесками утилизации (таких как spark или map reduce), которые основаны на расписании и где отказ не является критическим - спотовые инстансы являются наилучшим кандидатом.\n\t\t-\tВремя, необходимое для удовлетворения ставки на спот рынке и получения инстанса, может варьироваться от 2 до 10 минут в зависимости от типа инстанса и наличия машин в этой зоне доступности.\n\t\t-\tЕсли вы используете инфраструктуру с сотнями задач, с вероятностью резких нагрузок, рекомендуется начать объединять инстансы, чтобы оптимизировать затраты, производительность и, что наиболее важно, время на приобретение инстансов.\n\t\t-\tОбъединение в пул подразумевает создание и обслуживание спот инстансов таким образом, чтобы после выполнения задачи они не отключались. Это способствует повторному использованию спот инстансов для исполнения различных задач. Это, конечно, связано с накладными расходами на управление жизненным циклом.\n\t\t-\tПул имеет свой собственный набор показателей, которые можно отслеживать для оптимизации использования ресурсов, эффективности и стоимости.\n\t\t-\tТипичные реализации пула позволяют оптимизировать затраты на 45-60% и сократить время создания спот инстанса на 40%.\n\t\t-\tОтличный пример реализации пула, описанный Netflix ([часть 1](http://techblog.netflix.com/2015/09/creating-your-own-ec2-spot-market.html), [часть 2](http://techblog.netflix.com/2015/11/creating-your-own-ec2-spot-market-part-2.html)\\)\n-\t**Возможные ошибки в управление спотовыми ресурсами**\n\t-\t🔸**Время жизни:** Нет никаких [гарантий](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html) времени жизни спотового инстанса. Это основывается чисто на основе ставок. Если кто-то перебивает вашу ставку, то он забирает инстанс. Спотовые инстансы не подходят для задач, критичных ко времени работы или имеющих жесткий SLA.  Инстансы будут отключены из-за повышения спроса в текущий момент времени. AWS предоставляет [двухминутное предупреждение](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#spot-instance-termination-notices) перед тем, как Amazon отключит ваши спотовые EC2 инстансы.\n\t-\t🔹**Возврат данных от API:** - API Spot price возвращает данные о ценах спотовых инстансов с различной гранулярностью в зависимости от временного диапазона, указанного в запросе при вызове API. Таким образом, если были запрошены данные за последние 10 минут, ответ будет более гранулированным. А если же будет произведен запрос данных за последние два дня, выборка данных будет более грубой. Не расчитывайте на то, что вы получите все записи данных. **Будут** пропущенные интервалы.\n\t-\t❗**Управление жизненным циклом:** Не пытайтесь применять какие нибудь модные инструменты управления спотовыми инстансами до тех пор, пока это не станет абсолютно необходимым. Если вы используете всего несколько машин и цена вас полностью устраивает, а уровень отказов мал, не пытайтесь оптимизровать. Те страдания, которые вы испытаете в процессе создания/поддержки этого решения, не стоит нескольких сотен долларов экономии. \n-\t**Зарезервированные инстансы:** позволяют вам получить значительные скидки на цену вычислительного часа EC2 в обмен на  обязательство оплачивать вычислительные часы инстансов определенного типа в конкретной зоне доступности и регионе AWS, и в течение заранее установленного периода времени (1 или 3 года). Дополнительные скидки могут быть получены путем “частичной” или “полной” предоплаты.\n\t-\tРассмотрите возможность использования зарезервированных инстансов, когда вы можете спрогнозировать свои потребности в вычислениях в долгосрочном периоде и нуждаетесь в более надежной гарантии доступности и непрерывности вычислений, чем может обеспечить (как правило, более дешевый) спотовый рынок. Однако имейте в виду, что если ваша архитектура изменится, ваши вычислительные потребности также могут измениться, поэтому, хотя долгосрочные контракты могут показаться привлекательными, они могут оказаться громоздкими и неудобными.\n\t-\tСуществует два типа зарезервированных инстансов - [Стандартный и изменяемый(Standard and Convertible)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/reserved-instances-types.html). Если вы купили лишние стандартные зарезервированные инстансы, вы можете предложить неиспользованные зарезервированные инстансы “на продажу” путем размещения на [рынке зарезервированных инстансов(Reserved Instance Marketplace)](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-selling-guide.html), это позволяет вам частично компенсировать стоимость неиспользованных вычислительных часов инстансов EC2 путем продажи другим клиентам AWS.\n\t-\tЗарезервированные инстансы не привязаны к конкретным инстансам EC2 - они применяются на уровне выставления счетов к соответсвующим вычислительным часам, поскольку они потребляются всеми соответствующими инстансами в учетной записи.\n\t-\t📜Были разрозненные сообщения о том, что покупки изменяемых зарезервированных инстансов должны осуществляться в блоке, а именно: если вы покупаете изменяемых зарезервированных инстансов за одну покупку, вы не сможете конвертировать только два из них. Обратитесь к менеджеру своего аккаунта за разъяснениями, если это может повлиять на вас.\n-\tЕсли у вас несколько учетных записей AWS и вы настроили их на списание затрат с одной учетной записи, используя функцию “Консолидированного выставления счетов(Consolidated Billing)”, вы можете ожидать, что *неиспользованные* вычислительные часы зарезервированных инстансов с одной учетной записи будут списаны на соответствующие (по региону, зоне доступности, типу инстанса) вычислительные часы с другого аккаунта.\n-\tЕсли у вас есть несколько учетных записей AWS, связанных функцией консолидированного выставления счетов, и вы планируете использовать зарезервированные инстансы и, в то же время, хотите использовать неиспользованную зарезервированную емкость вычислительных часов с других учетных записей, вам необходимо создать ваши инстансы в зоне доступности, с тем же *именем*, что и в других учетных записях. Помните, что когда вы это сделаете, ваши инстансы могут оказаться не в тех же *физических* дата центрах, что и в других учетных записях - Amazon перемешивает названия зон доступности в разных учетных записях, в целях равномерного распределения ресурсов.\n-\tИспользуйте динамическое [автоматическое масштабирование](#auto-scaling-автоматическое-масштабирование), где возможно, в целях обеспечения лучшего соответствия размеров (и цены) вашего кластера к конкретным требованиям к ресурсам вашего сервиса.\n-\tЕсли вы используете инстансы на RHEL и так случилось, что у вас есть действующая подписка Red Hat, тогда вы можете участвовать в программе [Red Hat's Cloud Access](https://www.redhat.com/en/technologies/cloud-computing/cloud-access), чтобы перенести часть ваших локальных подписок в AWS и, таким образом сократить расходы на оплату подписок RHEL в AWS. Также вы можете использовать свои собсвенные AMI на основе RHEL или представленные Red Hat [золотые образы(Gold Images)](https://access.redhat.com/articles/2962171), которые будут добавлены в ваши частные AMI сразу после регистрации в Red Hat Cloud Access.\n\nДополнительные материалы\n---------------\n\nЭтот раздел охватывает несколько необычайно полезных и «обязательных для ознакомления» ресурсов или списков.\n\n-\tAWS\n\t-\t[AWS In Plain English](https://www.expeditedssl.com/aws-in-plain-english): Удобно излагаемый обзор сервисов AWS.\n\t-\t[Awesome AWS](https://github.com/donnemartin/awesome-aws): Отслеживаемый список продуктов и сервисов AWS.\n\t-\t[AWS Tips I Wish I'd Known Before I Started](https://wblinks.com/notes/aws-tips-i-wish-id-known-before-i-started/): Сборник советов от [Rich Adams](https://richadams.me/)\n\t-\t[AWS Whitepapers](https://aws.amazon.com/whitepapers/): Сборник официальных WhitePapers от AWS включающий в себя лучшие практики по организации доступности, безопасности и оптимизации расходов.\n\t-\t[Last Week in AWS](https://lastweekinaws.com): Еженедельник, освещающий последние события в AWS.\n\t-\t[AWS Geek](https://www.awsgeek.com): Блог AWS Community Hero Jerry Hargrove, с заметками и нарисованными от руки диаграммами о различных сервисах AWS.\n-\tКниги\n\t-\t[Amazon Web Services in Action](https://www.manning.com/books/amazon-web-services-in-action)\n\t-\t[AWS Lambda in Action](https://www.manning.com/books/aws-lambda-in-action)\n\t-\t[Serverless Architectures on AWS](https://www.manning.com/books/serverless-architectures-on-aws)\n\t-\t[Serverless Single Page Apps](https://pragprog.com/book/brapps/serverless-single-page-apps)\n\t-\t[The Terraform Book](https://terraformbook.com/)\n\t-\t[AWS Scripted 2 book series](https://www.amazon.com/gp/product/B016QBB0GO?ref=series_rw_dp_labf)\n\t-\t[Amazon Web Services For Dummies](https://www.amazon.com/dp/1118571835)\n\t-\t[AWS System Administration](http://shop.oreilly.com/product/0636920027638.do)\n\t-\t[Python and AWS Cookbook](http://shop.oreilly.com/product/0636920020202.do)\n\t-\t[Resilience and Reliability on AWS](http://shop.oreilly.com/product/0636920026839.do)\n\t-\t[AWS documentation as Kindle ebooks](https://www.amazon.com/Amazon-Web-Services/e/B007R6MVQ6)\n-\tОбщие ссылки на руководства\n\t-\t[AWS Well Architected Framework Guide](https://d0.awsstatic.com/whitepapers/architecture/AWS_Well-Architected_Framework.pdf): Официальное руководство по лучшим практикам по вопросам cloud архитектуры в AWS.\n\t-\t[Awesome Microservices](https://github.com/mfornos/awesome-microservices): Отслеживаемый список инструментов и технологий для микросервисных архитектур. Стоит просмотреть, чтобы узнать о популярных проектах с открытым исходным кодом..\n\t-\t[Is it fast yet?](https://istlsfastyet.com/): Обзор производительности сервисов на основе TLS от Ilya Grigorik\n\t-\t[High Performance Browser Networking](https://hpbn.co/): Полная, современная книга о производительности веб-сети; презентация в части HTTP / 2 [тут](https://docs.google.com/presentation/d/1r7QXGYOLCh4fcUq0jDdDwKJWNqWK1o4xMtYpKZCJYjM/edit?usp=sharing).\n\nОтказ от ответственности\n----------\n\nАвторы и соавторы данного произведения не могут гарантировать достоверность информации представленной в данном документе. Пожалуйста, удостоверьтесь, что вы понимаете, что информация представленная здесь, представлена бесплатно, и между вами и авторами данного документа/проекта нет никаких соглашений и контрактов. Авторы и добровольные участники проекта не несут никакой ответственности за любые потери, повреждения или сбои, вызванные ошибками или упущениями в информации, содержащейся в данном документе или как-то связанной с ним, независимо от того, вызваны ли такие ошибки или упущения халатностью, несчастным случаем или любой другой причиной.\n\nИнформация о лицензии\n-------\n\n[![Creative Commons License](https://i.creativecommons.org/l/by-sa/4.0/88x31.png)](http://creativecommons.org/licenses/by-sa/4.0/)\n\nЭто произведение лицензировано согласно [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/).\n"
  }
]